user2331095
user2331095

Reputation: 6707

angularjs controller in directive using controllerAs can not work?

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?

Upvotes: 13

Views: 9231

Answers (2)

Pascal Precht
Pascal Precht

Reputation: 8893

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.

Upvotes: -1

ControllerAs 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.

Upvotes: 16

Related Questions