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

I recently read John Pap, a self-confident AngularJS configuration guide, and noticed his agreement on controllers:

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

When this is used in the controller, it works fine, as you can do something like this (example):

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

However, I'm more curious how this 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 not 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 does this work in the directive? I tried using:

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

And nobody is working. As you can see, I shoot in the dark and do not understand the differences and how I can use this in Angular instead of scope . Also, since this is not a convention, I have not been able to find many resources talking to it, since it understands JS more than Angular.

Any help is appreciated!

+5
source share
2 answers

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

Your directive will look like this:

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

I believe controller: 'exampleCtrl as controller' also works. I have to confirm, but I'm too lazy, this. 😊

0
source

Source: https://habr.com/ru/post/1200125/


All Articles