2016-12-28 25 views
0
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'第一次。看起来this.valueuseExample在回调触发时没有更新。

我想获得新价值而不是旧价值。

我试图将的example更改为类似$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 *。

+0

可能重复[AngularJS:父范围没有更新在指令(与隔离范围)双向绑定](http://stackoverflow.com/questions/22557599/angularjs-parent-scope-is-not-updated- in-directive-with-isolated-scope-two-wa) – tsh

回答

0

问题是,绑定从子作用域到父作用域的值的监视器在调用表达式绑定中的函数后,在微线程(光纤)上执行。

的解决方案是,以暴露值作为表达式绑定本地:

myApp.component('example', { 
    template: '<button type="button" ng-click="$ctrl.click()">click me</button>', 
    bindings: { 
     callback: '&' 
    }, 
    controller: function() { 
     this.click = () => { 
     this.value = 'clicked'; 
     //EXPOSE this.value as $value 
     this.callback({$value: this.value}); 
     }; 
    }, 
}); 

在上述例子中,该值被公开为$value

使用曝光值作为回调函数的自变量:

myApp.component('useExample', { 
    template: '<example callback="$ctrl.useCallback($value)"></example>', 
    controller: function() { 
     this.useCallback = (v) => { alert(v); }; 
    }, 
}); 

,因为该值作为回调的参数设置,该值是立即可用。

The DEMO on JSFiddle

+0

在回调中传递值不是我想要的。因为它会改变我的组件的接口,并使调用者更加混淆。 (调用者不是由我写的) – tsh

+0

我只是希望它能像''input ng-model =“value”ng-change =“callback()”/>'那样工作,这看起来更好,而且看起来更像'stander'的方式。 – tsh