Reputation: 1857
I can't set a scope variable inside my custom directive's controller.
See this plkr: http://plnkr.co/edit/KVGVxhgRHxkhCLytkLBv?p=preview
Link function prints the variable name
but interpolator does not evaluate {{name}}
. I set it in the controller of my custom directive with isolate scope. Still for some reason, scope variable does not persist. Is this behavior expected? If so what is the proper way to set scope variables?
Help is appreciated.
Upvotes: 1
Views: 2780
Reputation: 52847
Import 'name' from your outside scope into your isolated scope using '=' binding:
// Code goes here
angular.module('test', [])
.directive('nametag', function() {
return {
scope: { name: '='},
controller: function($scope, $attrs, $log) {
$scope.name = 'John Doe';
},
link: function(scope, elem, attrs) {
// elem.text(scope.name);
}
};
});
HTML:
<div ng-app="app" ng-init="name='james'>
<nametag name="name"></nametag>
</div>
When you define an isolated scope for your directive (by specifying scope: {}
) you create a private scope that does not prototypically inherit from the parent scope. You can think of an isolated scope as your directive's private sandbox.
Since your directive's scope is isolated, you need to import scope variables from parent scope into your isolated scope through attribute bindings. In this case we are establishing two-way binding between the parent scope variable 'name', and the directive's isolated scope variable with the same name.
Upvotes: 3
Reputation: 16624
Your directive controller assigns the name to the isolated scope of the directive. So you have two possibilities:
Remove the scope: {}
from your directive to not create an isolated scope. While this works it is maybe not what you want as your directive modifies the outer scope.
Add a template to your diective containing the <h1>Hello {{name}}</h1>
. See this plunker.
Upvotes: 2