Using “this” instead of “scope” with AngularJS controllers and directives

拜拜、爱过 提交于 2019-12-30 20:58:10

问题


I was recently reading John Papa's opinionated AngularJS style guide and noticed his convention on controllers:

/* recommended */
function Customer () {
  var vm = this;
  vm.name = {};
  vm.sendMessage = function () { };
}

When this is used in a controller it works just fine as you can do something like this (his example):

<!-- recommended -->
<div ng-controller="Customer as customer">
    {{ customer.name }}
</div>

However I am more curious in how it works with directives that rely on this controller. For example, using $scope on my controller I can do something like this:

testModule.directive("example", function(){
    return{
        template: "Hello {{customer}}",
        controller: "exampleCtrl"
    }
});
testModule.controller("exampleCtrl", exampleCtrl);
function exampleCtrl($scope){
    $scope.message = "Display this";
}

But I can't do this using this.message:

testModule.directive("example", function(){
    return{
        template: "Hello {{customer}}", //Doesn't work!
        controller: "exampleCtrl"
    }
});
testModule.controller("exampleCtrl", exampleCtrl);
function exampleCtrl(){
    var vm = this;
    vm.message = "Display this";
}

So my question is, how would this work in the directive? I've tried using:

{{customer}}
{{this.customer}}
{{exampleCtrl.customer}}

And none work. As you can see, I'm shooting in the dark and not really understanding the differences and how I could use this in Angular instead of scope. Also, as this isn't the convention, I haven't been able to find many resources speaking to it, since it's more a JS understanding thing than Angular.

Any help is appreciated!


回答1:


When using this style, directives should use the controllerAs property in their return object per the Directive documentation.

Your directive would end up looking like:

testModule.directive("example", function() {
    return {
        template: "Hello {{controller.customer}}",
        controller: "exampleCtrl",
        controllerAs: "controller"
    };
});



回答2:


I believe that controller: 'exampleCtrl as controller' also works. I should confirm but I'm too lazy this a.m. 😊



来源:https://stackoverflow.com/questions/25266555/using-this-instead-of-scope-with-angularjs-controllers-and-directives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!