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, with the second one utilizing the functionality of the first component.
In the first component, the value is changed to 'clicked'
and then the callback is triggered. However, when the second component uses alert(this.value)
, it retrieves an empty value instead of 'clicked'
as expected. It appears that the this.value
in useExample
is not being updated when the callback is executed.
I am aiming to retrieve the new value rather than the old one.
I have experimented with changing this.callback()
in example
to something like
$timeout(function () { this.callback(); }.bind(this), 0)
, which did resolve the issue. However, I believe there might be a better approach to handle this situation.
Therefore, my question is what would be the optimal way to ensure that useExample
can access the updated this.value
within the callback.
-- Update 1 --
I prefer not to modify the existing interface.
-- Update 2 --
Ah, after conducting some research on this topic, I came across this thread: AngularJS: Parent scope is not updated in directive (with isolated scope) two way binding. It seems that this question mirrors the one discussed in that thread. Having read through the responses on that post, it appears that using $timeout
may be the suggested solution - quite frustrating.