在AngularJs控制器之间的通信 [英] Communicating between controllers in AngularJs

查看:141
本文介绍了在AngularJs控制器之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题:什么是最好的('干净','可扩展')的路径,当谈到之间的互动应该去(比方说)两个控制器。那会是为了应对定义服务和观看该服务的返回值?

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?

我设置一个简单的例子 rel=\"nofollow\">,我在那里观看了服务的当前值:

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?

干杯。

推荐答案

您的情况下试图在控制器控制器之间共享数据,而不是看服务的价值,我想直接引用服务对象控制器的范围是一个更好的办法

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

所以,你的看法可能是

 <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>

和改变你的控制器

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);
  }
});

使用$广播/ $发出

正如@squiroid指出的那样,你可以使用 $广播广播事件谁是监测有针对性的活动的控制器。

Use $broadcast/$emit

Just as @squiroid points out, you can use $broadcast to broadcast events to any controllers who is monitoring targeted events.

请注意这里,你最好不要使用 $ rootScope。$直播+ $范围。$关于而是 $ rootScope。$放出+ $ rootScope。$在 $广播活动将泡沫向下通过所有子范围,这可能会导致严重的性能问题。

Please note here, you'd better not use $rootScope.$broadcast + $scope.$on but rather $rootScope.$emit+ $rootScope.$onas $broadcast event will bubble down through all descendant scopes, which might lead to serious performance problems.

这篇关于在AngularJs控制器之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆