【问题标题】:Angular Directive to overwrite the parameters of another directiveAngular 指令覆盖另一个指令的参数
【发布时间】:2017-02-17 15:32:51
【问题描述】:

我有一个现有的指令,我不想碰它,它是这样使用的:

<div other-directive value="xyz"></div>

问题是,指令需要很多参数,我不想每次都写。所以我的想法是添加一个进一步的指令,预先设置这些参数。

<div my-directive other-directive></div>

我的覆盖机制如下所示:

angular.module('myApp')
  .directive("otherDirective", function(){
    return {
        restrict: "EA",
        template: '<i>{{value}}</i>',
        scope: {
            value: "=value"
        }
    };
  })

  // overwrite "value" parameter
  .directive("myDirective", function(){
    return {
        priority: 1000,
        restrict: "A",
        link: function(scope, element, attributes) {
          attributes.value = "Hello";
          attributes.$set('value', 'Hello');
        }
    };
  });

第二个指令似乎无法更改第一个指令的参数。 请看我的 Plunker:http://plnkr.co/edit/HutmraGNm9U1RKl5OD2S?p=preview

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    由于指令生命周期,上面的代码将不起作用。在指令函数中link 是最后执行的,此时other-directive 已经编译完成。相反,它应该是

    compile: function(element, attributes) {
      attributes.value = "Hello";
      attributes.$set('value', 'Hello');
    }
    

    顺便说一句,= 绑定会产生空值,因为作用域上没有 Hello 属性。应该是@

    但是,这是一个 hack。这样做的惯用方法是用另一个指令包装 other-directive 并在模板中提供所需的属性。

    【讨论】:

    • 谢谢 - 使用“编译”它可以工作!如何“提供模板中的属性”?
    • template: '&lt;div other-directive value="xyz"&gt;' 这样的包装指令。除非嵌套标签或范围会导致问题,否则这是可行的方法。
    猜你喜欢
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 2016-12-22
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多