Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different kind of Angular Directives patterns

Tags:

angularjs

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 pattern ?

like image 476
praveenpds Avatar asked Jul 29 '12 17:07

praveenpds


2 Answers

If you declare your factories with the bracket notation, you can avoid problems when minifying your code:

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

}]);

The injector looks at your function parameter names in order to know what to inject. If a minification process renames those, The injector doesn't know what to do anymore. Minification will of course not touch string values which is why the array notation works fine.

like image 108
moritz Avatar answered Oct 19 '22 06:10

moritz


The difference is that version #1 is a simple way that angular does support for writing directives that don't require any injectable modules. The version #2 is for having injectables. So, let's say your directive relied on the $timeout service, then you would have a definition like below. For me, its easier to not think and just use the array syntax even if there are no injectables.

angular.directive('ppd:reset', ['$timeout', function($timeout) { 
       return function(scope, elm, attrs) {   } 
}]);  
like image 4
Dan Doyon Avatar answered Oct 19 '22 05:10

Dan Doyon