如何在值更改时执行函数?

Fra*_*ste 2 angularjs

我有一个主控制器,还有另外两个控制器:

<div ng-controller="mainController" ng-model="value">
    <div ng-controller="otherController"></diV>
    <div ng-controller="anOtherController"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

由于控制器继承,我otherController可以更新我valueng-modeldiretive 绑定.

但我怎么能看到我anOtherControllervalue人为了执行由anOtherController拥有的功能改变了吗?

我可以为这个值注册一个函数吗?

Dal*_*rzo 9

你可以在你的控制器中做到这一点..

$scope.$watch("value",function(newValue,oldValue){
 // your code goes here...
});
Run Code Online (Sandbox Code Playgroud)

它基本上会监视给定"范围属性"的任何更改.但是,我的建议是使用服务或工厂.

请参考其他SO讨论:

AngularJS服务在控制器之间传递数据


ths*_*ens 5

向其他范围发送消息:

$scope.$broadcast('messagename', params);
Run Code Online (Sandbox Code Playgroud)

抓住它:

$scope.$on('messagename', function(params){
    alert('something happend');
});
Run Code Online (Sandbox Code Playgroud)

范围向下继承;如果您希望将消息发送到所有范围,请使用$rootScope.$broadcast

或者您可以简单地添加一个观察者。