动态更改Angular指令元素属性

时间:2014-10-22 11:52:03

标签: angularjs angularjs-directive

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

我试图在预编译期间实现这一点,但angular不会对添加新属性做出反应。

created a plunker使用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){

                 }
             }
         },
      };
    });

如果我添加ng-hide =&#34; true&#34;在HTML中,然后正确隐藏提交按钮。如果我把它留给指令那么我可以看到DOM正确设置了元素但是元素没有被隐藏:

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

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:20)

您可以通过

在链接功能中执行此操作
  • 将指令的优先级设置为高,因此它在所有其他指令之前运行。
  • 将其设置为终端,以便其他人不要追踪它。
  • 对元素进行更改后重新编译元素(例如添加属性)

例如:

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);
   }
  };
});

可以在http://plnkr.co/edit/tHNvCxVn2wURO38UtI0n?p=preview

上看到
相关问题