Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isolate scope directive with optional ampersand binding in angularjs?

Tags:

angularjs

Can one create a isolate scope with optional ampersand (parent context) data binding?

scope: {
  myMethod: '&?'
}

If the directive is implemented without assigning myMethod, there is no error. However, I see that when the optional property is not assigned, angular assigns it a noop function anyways. Therefore, there appears to be no way to know, within the directive, if the implementer assigned the optional property a method or not.

link: function (scope, element, attrs) {
 scope.myMethod(); //this calls a noop function instead of being undefined, as i exected
}

Any insights? I'd like to know if the implementor has assigned the optional property.

like image 800
Paul Avatar asked Jul 09 '14 20:07

Paul


2 Answers

Check the attrs object to see if it was populated:

link: function (scope, element, attrs) {
    if (attrs.myMethod) {
        scope.myMethod();
    }
}
like image 51
DRiFTy Avatar answered Nov 10 '22 07:11

DRiFTy


Using '&?' returns undefined if the attribute has not been set.

https://github.com/angular/angular.js/commit/6a38dbfd3c34c8f9efff503d17eb3cbeb666d422

like image 37
Sam Dawson Avatar answered Nov 10 '22 08:11

Sam Dawson