Gianpiero Caretti Gianpiero Caretti - 1 year ago 79
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 Source

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 ){ .... }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download