【问题标题】:Angular optional attribute in directive指令中的 Angular 可选属性
【发布时间】:2015-10-15 05:49:13
【问题描述】:

我有一个指令:

angular
  .module('test')
  .directive('multiButton', function () {
    return {
      restrict: 'E',
      replace: true,
      scope: {
        disabled: '@'
      },
      template: '<div class="multi-button"><button ng-disabled={{disabled}}></button></div>'
    });

禁用范围属性是可选的,但如果没有提交禁用属性,我不想在渲染时在我的模板中包含“ng-disabled”内容。

这可能吗?如果是的话怎么办?

【问题讨论】:

  • disabled: '@?'? 运算符。 stackoverflow.com/a/20447939/624590
  • @DRobinson 当然,但是当模板被渲染时,它会有“ng-disabled”,对吗?这就是我要防止的。
  • 啊,有道理。那么您可能希望@?compile 函数结合使用来构建模板字符串。
  • @randomKek 你要动态设置disabled 值吗
  • 实际上,编译过于复杂。链接更有意义。更新了我的答案以简化它。

标签: javascript angularjs


【解决方案1】:

您可以检查链接上是否存在该属性,如果存在则添加相关的(ngDisabled)属性:

angular.module('myApp',[])
    .directive('multiButton', function () {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                disabled: '@?'
            },
            template: '<div class="multi-button"><button></button></div>',
            link: function(scope, element, attr){
                if(attr.disabled){
                    element.find('button').attr('ng-disabled', attr.disabled);
                }
            }
        }
    });

演示小提琴:http://jsfiddle.net/guv11rxq/

现在,正如预期的那样,&lt;multi-button disabled="hello"&gt;&lt;/multi-button&gt; 将导致:

&lt;div class="multi-button"&gt;&lt;button ng-disabled="hello"&gt;&lt;/button&gt;&lt;/div&gt;

但如果没有可选属性&lt;multi-button&gt;&lt;/multi-button&gt;,则会导致:

&lt;div class="multi-button"&gt;&lt;button&gt;&lt;/button&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:

    您可以通过在模板中使用 ng-if 来做到这一点:

     template: '<div class="multi-button" ng-if="disabled != ''"><button ng-disabled={{disabled}}></button></div><div class="multi-button" ng-if="disabled === ''"><button></button></div>'
    

    【讨论】:

    • 这增加了很多额外的模板代码来维护(任何更改都必须在两个地方进行,在编写代码时应该经常避免 - 目标是 DRY)。此外,这是一个小得多的问题,它会在每个 $digest 循环中为每个元素添加两次比较。
    • @DRobinson 你是对的。这不是最好的方法,但您仍然可以使用它。
    • 是的,我同意原则上这基本上是可行的,尽管非常不理想。由于我在上面的评论中概述的原因,这是一种应该避免的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 2014-09-07
    • 1970-01-01
    相关资源
    最近更新 更多