将其他指令添加到angular.js中的同一元素的指令

时间:2021-05-05 12:09:37

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'/>

2 个解决方案

#1


3  

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

我不认为$ compile(),链接函数或终端是必需的。 Angular将自动为我们编制电话。

.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:

使用此HTML进行测试:

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

Plunker.

#2


1  

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.

关键是要确保指令的优先级高于元素上的所有其他指令并终止,以便其他指令不被编译和链接。

#1


3  

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

我不认为$ compile(),链接函数或终端是必需的。 Angular将自动为我们编制电话。

.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:

使用此HTML进行测试:

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

Plunker.

#2


1  

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.

关键是要确保指令的优先级高于元素上的所有其他指令并终止,以便其他指令不被编译和链接。