Different types of Angular directive templates

angular.directive('ppd:reset', function(e1,e2) { return function(linkElement) { linkElement.wrap().... }); }; }); 

AND

 angular.directive('ppd:reset', [function() { return function(scope, elm, attrs) { } }]); 

What is the difference between these two directives?

+6
source share
3 answers

If you declare your factories with a musical bracket, you can avoid the problems of shortening the code:

 angular.directive('ppd:reset', ["$compile", function(compile) { return function(scope, elm, attrs) { } }]); 

The injector scans your function parameter names to know what to enter. If the minimization process renames them, the injector does not know what to do next. Of course, minimization will not affect string values, so array notation works fine.

+17
source

The difference is that version # 1 is an easy way for angular to support writing directives that do not require injection modules. Version number 2 is for injection. So, let's say your directive relied on the $ timeout service, then you will have such a definition, as shown below. For me it is easier not to think about it and just use the array syntax, even if there are no injections.

 angular.directive('ppd:reset', ['$timeout', function($timeout) { return function(scope, elm, attrs) { } }]); 
+4
source

The difference between the two is that the notation [] bracket minifier -safe as minifiers does not minimize lines. For example, if you try to minimize javascript without it, it will turn:

 angular.module('myApp', []) .controller('MainController', function($scope) { }); 

in

 angular.module("myApp",[]).controller("MainController",function(e){}) 

The problem in this case is that Angular knows nothing about e , not about the $scope that it knows about. Using the [] notation, we can tell $injector in advance that we want the controller to gain access. Since minifiers do not (and cannot) minimize strings, this is a safe way to use the Angular injection function with or without minifiers.

For a deeper understanding of syntax differences, you can check out ng-book ( https://www.ng-book.com/ ). Disclaimer, I am the author of the book and http://www.ng-newsletter.com/ .

0
source

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


All Articles