I am trying to put some data in the scope which my directive create. Here is my jsFiddle.
the following code works well
.directive('directive1', function () {
return: {
scope: true,
controller: function ($scope) {
$scope.name = 'world';
}
}
})
<div directive1>
<p>{{ name }}</p>
</div>
but these code do not work
.directive('directive2', function () {
return: {
scope: true,
controller: function () {
this.name = 'world';
},
controllerAs: 'testCtrl'
}
})
<div directive2>
<p>{{ testCtrl.name }}</p>
</div>
Is there anything wrong in my code? or did I misunderstand something about controllerAs
?
I am trying to put some data in the scope which my directive create. Here is my jsFiddle.
the following code works well
.directive('directive1', function () {
return: {
scope: true,
controller: function ($scope) {
$scope.name = 'world';
}
}
})
<div directive1>
<p>{{ name }}</p>
</div>
but these code do not work
.directive('directive2', function () {
return: {
scope: true,
controller: function () {
this.name = 'world';
},
controllerAs: 'testCtrl'
}
})
<div directive2>
<p>{{ testCtrl.name }}</p>
</div>
Is there anything wrong in my code? or did I misunderstand something about controllerAs
?
2 Answers
Reset to default 16ControllerAs support for directives was added in 1.2.0, so you'll have to use most recent version, instead of 1.0.2
from linked fiddle. This way it works like you wanted.
Please do not confuse with directive controller and a normal controller! So yea, a directve can have a controller, which controls something. But it's not equivalent to a normal controller!
There isn't actually a problem to put directive logic into directive controller, but the directive controller actually, is used for cross directive communication. A controller instance of one directive can be injected into another directive which sits on the same element (or child elements).
The "controller as" expression is for normal controllers. So just do your self a favour and put your logic into directives link function.
$scope
. What iscontrollerAs
? – Maxim Shoustin Commented Sep 21, 2013 at 11:01