5

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!

2 Answers 2

11

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"
    };
});
Sign up to request clarification or add additional context in comments.

4 Comments

Too easy, should have dug even further into the documentation. Thanks!
Thanks for answering ... I will add a note to add this to my style guide. I probably shoulda had it already :)
Added this to my angularjs style guide github.com/johnpapa/angularjs-styleguide/commit/…
what about isolated scope concept?
0

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

Comments

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.