How to check if a method argument of a directive is specified in AngularJS?

前端 未结 2 913
北荒
北荒 2020-12-02 18:31

I\'ve created a custom directive which contains a button. This button calls a method from parent scope specified by \'callback\' attribute.



        
相关标签:
2条回答
  • 2020-12-02 18:50

    Using '&?' returns undefined if the attribute has not been set.

    '&' = callback function is defined always.

    '&?' = callback function is defined only when attribute is defined in html template.

    bindToController: {
        callback: '&?'
    },
    controller: function() {
        if (this.callback === undefined) {
            // attribute "callback" was not defined
        }
    }
    

    Note: Works in Angular 1.4.8. I'm not sure if it works in older versions.

    0 讨论(0)
  • 2020-12-02 19:10

    Looking at angularjs source code, I see this:

    case '&':
        parentGet = $parse(attrs[attrName]);
        isolateScope[scopeName] = function(locals) {
             return parentGet(scope, locals);
        };
        break;
    

    The parentGet is the bound function expression. Unfortunately, this is a local variable which is only available to the function assigned to isolateScope[scopeName] via closure.

    Instead of trying to find a way to get that variable, a simple solution is just to check the attrs. Try:

    link: function(scope,elem,attrs) {
    
          scope.hasCallback = function() {
            return angular.isDefined(attrs.callback);
          }
        }
    

    DEMO

    0 讨论(0)
提交回复
热议问题