AngularJs 中控制器之间的通信 [英] Communicating between controllers in AngularJs
问题描述
我有一个简单的问题:当涉及(假设)两个控制器之间的交互时,应该走的最佳(最干净"、可扩展")路径是什么.这是否是定义一个服务并观察该服务的返回值以便做出反应?
我在此处设置了一个简单示例,我在其中查看服务的当前值:
$scope.$watch(功能() {返回 myService.getValue();},功能(新值){$scope.value1 = newVal;});
并在单击其中一个按钮时更新该服务的值.
能否以某种方式做得更好、更小、更清洁?这里的最佳做法是什么?
干杯.
使用服务在控制器之间共享数据
您的案例试图在控制器之间共享数据,而不是在控制器中观察服务的价值,我认为将服务对象直接引用到控制器的范围是更好的方法
所以你的观点可以是
cntrl1中的值:{{ myService.value }}
并将您的控制器更改为
app.controller('cntrl1', function(myService, $scope) {$scope.myService = myService;$scope.update = function(str) {$scope.myService.setValue(str);}});app.controller('cntrl2', function(myService, $scope) {$scope.myService = myService;$scope.update = function(str) {$scope.myService.setValue(str);}});
使用 $broadcast/$emit
正如@squiroid 指出的那样,您可以使用 $broadcast
将事件广播给正在监控目标事件的任何控制器.
这里请注意,你最好不要使用 $rootScope.$broadcast + $scope.$on
而是使用 $rootScope.$emit+ $rootScope.$on
因为 $broadcast
事件会在所有后代作用域中冒泡,这可能会导致严重的性能问题.
I have a simple question: what's the best ('cleanest', 'scaleable') path one should go when it comes to interact between (let's say) two controllers. Would that be to define a service and watch that service's return-value in order to react?
I setup a simple example here, where I watch the service's current value:
$scope.$watch(
function() {
return myService.getValue();
},
function(newVal) {
$scope.value1 = newVal;
});
and update that service's value when one of the buttons is clicked.
Can this be done better, smaller, cleaner somehow? What's the best practice here?
Cheers.
Use service to share data between controllers
Your case is trying to share data between controllers, rather than watch service's value in controllers, I think directly reference service object to controller's scope is a better way
So your view can be
<pre ng-controller="cntrl1">Value in cntrl1: {{ myService.value }} <button ng-click="update('value1')">Change to 'value1'</button></pre>
<pre ng-controller="cntrl2">Value in cntrl2: {{ myService.value }} <button ng-click="update('value2')">Change to 'value2'</button></pre>
and change your controllers to
app.controller('cntrl1', function(myService, $scope) {
$scope.myService = myService;
$scope.update = function(str) {
$scope.myService.setValue(str);
}
});
app.controller('cntrl2', function(myService, $scope) {
$scope.myService = myService;
$scope.update = function(str) {
$scope.myService.setValue(str);
}
});
Use $broadcast/$emit
Just as @squiroid points out, you can use $broadcast
to broadcast events to any controllers who is monitoring targeted events.
Please note here, you'd better not use $rootScope.$broadcast + $scope.$on
but rather $rootScope.$emit+ $rootScope.$on
as $broadcast
event will bubble down through all descendant scopes, which might lead to serious performance problems.
这篇关于AngularJs 中控制器之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!