Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "this" instead of "scope" with AngularJS controllers and directives

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!

like image 203
Blunderfest Avatar asked Aug 12 '14 14:08

Blunderfest


1 Answers

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"
    };
});
like image 119
klyd Avatar answered Sep 21 '22 20:09

klyd