Can one directive have different names in angularjs?

I have two directives with the same functions as shown below.

angular.module('ui.directives', []) .directive('uiFoo', function() { return { restrict: 'EAC', link: function($scope, element, attrs) { //to do functionality element.append("test content"); } }; }) .directive('uiFoo1', function() { return { restrict: 'EAC', link: function($scope, element, attrs) { //to do functionality element.append("test content"); } }; }); 

Both of them contain the same thing as here, this adds “test content” as text to this element. Is it likely that you will do these two directives instead. Can I write two names for one directive / I can use the same functionality with code optimization. Here I write the same code without any meaning. Instead of writing the directive twice, is there any way to optimize. I am new to AngularJS, kindly help me. Thanks in advance!

+6
source share
1 answer

The easiest way is to extract your directive into a JS object and use it instead.

Alternatively, you can provide the directive object to the angular provider if you want to stay in the angular context.

But why do you want to have two directives with the same functionality in the first place?
Directives can be used as often as you want, so this seems like a design error to me.

 var myDirective = [function(){ restrict: 'EAC', link: function($scope, element, attrs) { //to do functionality element.append("test content"); } }]; angular.module('ui.directives', []) .directive('uiFoo', myDirective) .directive('uiFoo1', myDirective); 
+8
source

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


All Articles