How do you check if & variable is set in directive

坚强是说给别人听的谎言 提交于 2019-12-22 04:15:12

问题


In a directive, where you set a method callback through an arg, say:

<my-directive callback='showAlert()' />

You can retrieve the variable through the scope setting in the return:

scope: {
    callback: "&callback"
}

If the callback is not set, eg:

<my-directive />

The value of $scope.callback is still:

$scope.callback():function (locals) {
    return parentGet(scope, locals);
}

Is there a good way to check that the callback was not set?


回答1:


One way i can think off is to check the attribute parameter for the directive name like

link: function (scope, elm, attrs) {

   if(attrs.callback) {
       //this attribute has been defined.
   }

}



回答2:


You can use &? insteand of &. It will make $scope.callback equal to undefined if it is not provided.




回答3:


Because parameters that are passed to the directive will reside on the directive's scope, I prefer to check for type. Even thought it's defined as expression in the scope configuration:

scope: { callback: '&attrName' },
link: function(scope, ...){
    if (typeof scope.callback === 'function') {
        // do my stuff
    }
}

that way I always sure I'm getting what I expect.




回答4:


this approach worked for me:

scope: {
  callback: '&callback',
  callbackExists: '@callback'
}

Then using the second parameter in the template:

<div ng-if="callbackExists">…</div>



回答5:


use angular.isUndefined to check callback function

link: function(scope, element, attrs) {
    if (angular.isUndefined(scope.callback)) {
        // do something when callback undefined
        return;
    }
    // do something when callback defined
}


来源:https://stackoverflow.com/questions/21820151/how-do-you-check-if-variable-is-set-in-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!