13

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
  • I don't know if you can do that. You defined controller without $scope. What is controllerAs? Commented Sep 21, 2013 at 11:01
  • 1
    @MaximShoustin angular1.2 docs, a new feature for directive Commented Sep 21, 2013 at 15:08

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You are right. After migrating to angular 1.2, it works well. thanks~!
-1

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.

2 Comments

Thanks for the detail of controller! Actually I am confusing with a normal controller and directive controller. Thanks again!
This answer is misleading - a directive controller is the same as a normal controller, except that instead of being instantiated by the ngController directive, it's instantiated by the directive you associate it with. It works just the same, injectables, controllerAs, everything. Logic can/should go in a directive's controller - the link function should primarily be used for DOM manipulation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.