How do you check if & variable is set in directive

♀尐吖头ヾ 提交于 2019-12-05 03:40:32

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.
   }

}

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

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.

this approach worked for me:

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

Then using the second parameter in the template:

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

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