Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one directive have different names in angularjs?

I'm having two directives with same functionality like 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");
        }
      };
    });

They both contain the same working like here it is appending "test content" as text to that element. Is there any chance that instead making this two directive. Can i write two names for one directive/ I can use same functionality in with optimize code. Here I'm writing same code for without any meaning. Instead of writing directive two times, is there any optimize way. I'm new in AngularJS kindly help me. Thanks in advance!

like image 395
Pankaj Parkar Avatar asked Aug 20 '14 18:08

Pankaj Parkar


1 Answers

The simpliest way would be to extract your directive into a JS object and use this instead.

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

But, why do you want to have two directives with the exact same functionality in the first place?
Directives can used as often as you want, so this seems like a design flaw 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);
like image 173
Pr0gr4mm3r Avatar answered Oct 26 '22 04:10

Pr0gr4mm3r