简体   繁体   English

指令中的Angular可选属性

[英]Angular optional attribute in directive

I have a directive: 我有一条指令:

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

The disabled scope attribute is optional, but I don't want to have "ng-disabled" stuff in my template when rendered if no disabled attribute was submitted. 禁用的范围属性是可选的,但是如果没有提交任何禁用的属性,我不想在呈现时在模板中包含“ ng-disabled”的内容。

Is this possible? 这可能吗? And if so how? 如果是这样怎么办?

You can check if the attribute exists on link, and add the related ( ngDisabled ) attribute if so: 您可以检查链接上是否存在该属性,如果存在,则添加相关的( 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);
                }
            }
        }
    });

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

Now, as expected, <multi-button disabled="hello"></multi-button> will result in: 现在,如预期的那样, <multi-button disabled="hello"></multi-button>将导致:

<div class="multi-button"><button ng-disabled="hello"></button></div>

But without the optional attribute, <multi-button></multi-button> , it will result in: 但是如果没有可选属性<multi-button></multi-button> ,它将导致:

<div class="multi-button"><button></button></div>

您可以通过在模板中使用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>'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM