本文介绍了动态更改 Angular 指令元素属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个扩展现有元素功能的自定义指令.我想检测某个属性是否存在,如果不存在则添加它(例如 ng-class).

我在预编译期间尝试实现这一点,但 angular 对添加新属性没有反应.

创建了一个plunker,其中包含一个使用ng-hide 的简单示例.

app.directive('隐藏', function() {返回 {限制:'A',编译:函数(){返回 {前:功能(范围,元素,属性,控制器,transcludeFn){attributes.$set("ng-hide", true);},帖子:功能(范围,元素,属性,控制器,transcludeFn){}}},};});

如果我在 html 中添加 ng-hide="true" 则提交按钮被正确隐藏.如果我把它留给指令,那么我可以看到 DOM 的元素设置正确,但元素没有隐藏:

感谢任何帮助!

解决方案

你可以在链接函数中这样做

  • 将指令的优先级设置为高,使其在所有其他指令之前运行.
  • 将其设置为终端,这样其他人就不会在其后运行.
  • 对元素进行更改(例如添加属性)后重新编译该元素

例如:

app.directive('hide', function($compile) {返回 {限制:'A',优先级:10000,终端:真的,链接:函数(范围,元素,属性){attrs.$set('ngHide', true);attrs.$set('隐藏', null);$compile(element)(scope);}};});

正如在 http://plnkr.co/edit/tHNvCxVn2wURO38UtI0n?p=preview 上所见

I am trying to create a custom directive which extends the functionality of an existing element. I would like to detect if a certain attribute exists and if not then add it (e.g. ng-class).

I have tried to achieve this during pre-compilation but angular does not react to the addition of the new attribute.

I created a plunker with a simple example using ng-hide.

<input hide type="submit" value="Submit"/>


    app.directive('hide', function() {
      return {
        restrict: 'A',
        compile: function(){
             return {
                 pre: function(scope, element, attributes, controller, transcludeFn){
                   attributes.$set("ng-hide", true);
                 },
                 post: function(scope, element, attributes, controller, transcludeFn){

                 }
             }
         },
      };
    });

If I add ng-hide="true" in the html then the submit button is hidden correctly. If I leave it to the directive then I can see that the DOM has the element set up correctly but the element is not hidden:

<input hide="" type="submit" value="Submit" ng-hide="true">

Any help appreciated!

解决方案

You can do this in the linking function by

  • Setting the directive's priority high, so it runs before all others.
  • Set it to terminal, so others don't run after it.
  • Recompile the element after you make changes to it (such as adding attributes)

For example:

app.directive('hide', function($compile) {
  return {
    restrict: 'A',
    priority: 10000,
    terminal: true,
    link: function(scope, element, attrs) {
      attrs.$set('ngHide', true);
      attrs.$set('hide', null);
      $compile(element)(scope);
   }
  };
});

As can be seen on http://plnkr.co/edit/tHNvCxVn2wURO38UtI0n?p=preview

这篇关于动态更改 Angular 指令元素属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:01