Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

directive that adds other directives to the same element in angular.js

Tags:

angularjs

How do I create a directive that adds other directives to an element?

For example, I want:

<input tag/>

to be linked as:

<input ng-pattern='/[\\w\\d]+/' ng-maxlength='10'/>
like image 961
joshrtay Avatar asked Mar 21 '13 20:03

joshrtay


2 Answers

I don't think $compile(), a link function, or terminal are necessary. Angular will automatically compile the telement for us.

.directive('tag', [function() {
  return {
    priority: 1000,
    compile: function(telement, attrs) {
      attrs.$set('tag', null);
      attrs.$set('ngMaxlength', '10');
      attrs.$set('ngPattern', '/[\\w\\d]+/');
    }
  };
}]);

Tested with this HTML:

<input ng-model="test" ng-init="test=2" tag>
{{test}}

Plunker.

like image 181
Mark Rajcok Avatar answered Oct 07 '22 16:10

Mark Rajcok


I came up with a solution that seems to work:

.directive('tag', ['$compile', function($compile) {
  return {
    priority: 1000,
    terminal: true,
    compile: function(telement, attrs) {
      attrs.$set('tag', null);
      attrs.$set('ngMaxlength', '10');
      attrs.$set('ngPattern', '/[\\w\\d]+/');

      var link = $compile(telement);

      return function($scope, $element) {
        link($scope, function(clonedElement) {
         $element.replaceWith(clonedElement);
        });
      }
    }
  }
}]);

The key is making sure that the directive has a higher priority than all the other directives on the element and terminating, so that other directives arent compiled and linked.

like image 27
joshrtay Avatar answered Oct 07 '22 17:10

joshrtay