最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - angularjs controller in directive using controllerAs can not work? - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question edited Jan 10, 2014 at 11:10 Klaster_1 Нет войне 12.1k9 gold badges64 silver badges75 bronze badges asked Sep 21, 2013 at 10:45 user2331095user2331095 6,70710 gold badges39 silver badges61 bronze badges 2
  • I don't know if you can do that. You defined controller without $scope. What is controllerAs? – Maxim Shoustin Commented Sep 21, 2013 at 11:01
  • 1 @MaximShoustin angular1.2 docs, a new feature for directive – user2331095 Commented Sep 21, 2013 at 15:08
Add a comment  | 

2 Answers 2

Reset to default 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.

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.

发布评论

评论列表(0)

  1. 暂无评论