简体   繁体   中英

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.

Is this possible? And if so how?

You can check if the attribute exists on link, and add the related ( ngDisabled ) attribute if so:

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/

Now, as expected, <multi-button disabled="hello"></multi-button> will result in:

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

But without the optional attribute, <multi-button></multi-button> , it will result in:

<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>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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