myApp.component('example', {
template: '<button type="button" ng-click="$ctrl.click()">click me</button>',
bindings: { value: '=', callback: '&' },
controller: function () {
this.click = function () {
this.value = 'clicked';
this.callback();
}.bind(this);
},
});
myApp.component('useExample', {
template: '<example value="$ctrl.value" callback="$ctrl.callback()"></example>',
controller: function () {
this.callback = function () { alert(this.value); }.bind(this);
},
});
Here are two components, while the second one use the first one.
The first component change this.value
and then call callback
. But when the second one alert(this.value)
, it got empty value instead of 'clicked'
first time. It seems that the this.value
in useExample
did not be updated when the callback is triggered.
I want get new value instead of old one.
I have attempted to change this.callback()
in example
to something like $timeout(function () { this.callback(); }.bind(this), 0)
, and it works. But I think there should be some better way to do so.
So, my question is what is the best way I should do to make useExample
read new this.value
in the callback.
-- Update 1 --
I would prefer not to change the given interface.
-- Update 2 --
aha, i just searched out this topic: AngularJS: Parent scope is not updated in directive (with isolated scope) two way binding . It seems that this question is duplicate to that one. and i have read posts on that question, it seems $timeout
is the best(?) way, wt*.