Reputation: 1854
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!
Upvotes: 5
Views: 2716
Reputation: 17863
I believe that controller: 'exampleCtrl as controller'
also works. I should confirm but I'm too lazy this a.m. 😊
Upvotes: 0
Reputation: 3979
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"
};
});
Upvotes: 11