I have a (simplified) directive
angular.module('myApp')
.directive('myButton', function () {
return {
restrict: 'E',
scope: {
callbackFn: '&'
},
template: '<button ng-click=ca;;backFn($evenb)'
}
});
Now, in some parent controller I have defined a callback function:
this.myCallback = function ($event) {
this.doIt($event);
}
and the HTML:
<my-button callback-fn="page.myCallback()"></my-button>
(I'm using things like bindToController
and controllerAs
)
The issue is that the $event
is never passed to myCallback
, which most likely has to do with how I bind this function (&
). But on the other hand, inside myCallback
I would like to use this
.
Is there some way to fix this ? without doing things like
var self = this;
this.myCallback = function ($event) {
self.doIt($event);
}
Callback function is a function which is passed to a function as parameter and is executed when the outer function is completed. Callbacks are a feature of JavaScript not particularly angularjs. Its a way to send a function as a parameter to the callee so that the callee call that function once the task is finished.
bind() Function in AngularJS is used to bind the current context to a function, but actually, execute it at a later time. It can also be used in Partial Applications. Partial Application is when you want to make a function but some of the arguments have been passed already.
A callback function is a function which is scheduled to be called after some asynchronous processing is completed. The callback functions are passed to another function as parameters which allows them to be called when the async processing is completed.
You haven't completely set up your bindings correctly. You can pass back arguments from the directive to the parent controller via a key-value map. According to the angular docs (emphasis mine):
&
or&attr
- provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given<widget my-attr="count = count + value">
and widget definition ofscope: { localFn:'&myAttr'
}, then isolate scope propertylocalFn
will point to a function wrapper for thecount = count + value
expression. Often it's desirable to pass data from the isolated scope via an expression to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression isincrement(amount)
then we can specify the amount value by calling thelocalFn
aslocalFn({amount: 22})
.
So that means in your consuming HTML you need to add parameters:
<my-button callback-fn="page.myCallback(parentEvent)"></my-button>
And then in the directive:
......
restrict: 'E',
scope: {
callbackFn: '&'
},
template: '<button ng-click="ctrl.callbackFn({parentEvent: $event})">Callback</button>'
,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With