Gianpiero Caretti Gianpiero Caretti - 9 days ago 6
AngularJS Question

Angular 1.5 component check '& binding' is null

Please, help me on this point.

I have an angular 1.5 component using '& binding':

app.component('foo', {
bindings: {
message: '<'
onSomething: '&'
},
template:'<div>blah blah</div>',
controller: function () {
var ctrl = this;
ctrl.myOperation = function () {
ctrl.onSomething(); // <= look this!
}
}
});


And I'd like to test if 'onSomething' is defined.

In fact, if I use it in this way:

<foo message='my message' on-something='doSomething()'></foo>


all is ok.

But if I use it in this way:

<foo message='my message'></foo>


'onSomething' should not be defined, but I am not able to check it!

I tried:

if (ctrl.onSomething) ...
if (ctrl.onSomething == undefined) ...
if (ctrl.onSomething == null) ...
if (angular.isDefined(ctrl.onSomething)


all these tests always return 'true', even when the callback has not been passed.

Answer

They return true because ctrl.onSomething is a hook function for initiating the callback declared in the instance of the component. It will always be truthy. Instead, try injecting $attrs into your controller and null-check it.

function( $attrs ){
    var ctrl = this;
    ctrl.myOperation = function(){
        if( $attrs.onSomething ){ .... }
    }
}