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?
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
}
来源:https://stackoverflow.com/questions/21820151/how-do-you-check-if-variable-is-set-in-directive