【发布时间】:2016-12-28 09:24:35
【问题描述】:
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);
},
});
这里有两个组件,而第二个使用第一个。
第一个组件更改this.value,然后调用callback。但是当第二个alert(this.value) 时,它第一次得到空值而不是'clicked'。触发回调时,似乎useExample中的this.value没有更新。
我想获得新价值而不是旧价值。
我试图将example 中的this.callback() 更改为$timeout(function () { this.callback(); }.bind(this), 0) 之类的东西,它可以工作。但我认为应该有更好的方法来做到这一点。
所以,我的问题是在回调中让useExample 读取新的this.value 的最佳方法是什么。
-- 更新 1--
我不想改变给定的界面。
-- 更新 2--
啊哈,我刚搜到这个话题:AngularJS: Parent scope is not updated in directive (with isolated scope) two way binding。这个问题似乎与那个问题重复。我已经阅读过关于这个问题的帖子,看来$timeout 是最好的(?)方式,wt*。
【问题讨论】:
标签: javascript angularjs