我怎样才能从一个控制器的一些数据传递给另一个对等控制器 [英] How can I pass some data from one controller to another peer controller

查看:326
本文介绍了我怎样才能从一个控制器的一些数据传递给另一个对等控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个对等控制器。有没有父母这些:

I have the following two peer controllers. There's no parent to these:

<div data-ng-controller="Controller1">

</div>

<div data-ng-controller="Controller2">
   The value of xxx is: {{ xxx }}
</div>

angular.module('test')
   .controller('QuestionsStatusController1',
    ['$rootScope', '$scope'
    function ($rootScope, $scope) {
    // How can I set the value of xxx in the HTML that's part of Controller2    
    }]);

angular.module('test')
   .controller('QuestionsStatusController2',
    ['$rootScope', '$scope',
    function ($rootScope, $scope) {
    }]);

在控制器1我想更新该是由控制器2控制的HTML变量XXX的值。有没有一种方法可以让我做到这一点?

In controller 1 I want to update the value of the variable xxx in the HTML that's controlled by Controller2. Is there a way I can do this?

推荐答案

绝对使用服务控制器之间共享数据,这里是一个工作的例子。
$广播是不可去,你应该避免使用事件系统时,有一个更合适的方式的方式。使用服务,价值或不变(全局常量)。

Definitely use a service to share data between controllers, here is a working example. $broadcast is not the way to go, you should avoid using the eventing system when there is a more appropriate way. Use a 'service', 'value' or 'constant' (for global constants).

http://plnkr.co/edit/ETWU7d0O8Kaz6qpFP5Hp

下面是一个输入一个例子,所以你可以看到页面上的数据镜像:
http://plnkr.co/edit/DbBp60AgfbmGpgvwtnpU

Here is an example with an input so you can see the data mirror on the page: http://plnkr.co/edit/DbBp60AgfbmGpgvwtnpU

var testModule = angular.module('testmodule', []);

testModule
   .controller('QuestionsStatusController1',
    ['$rootScope', '$scope', 'myservice',
    function ($rootScope, $scope, myservice) {
       $scope.myservice = myservice;   
    }]);

testModule
   .controller('QuestionsStatusController2',
    ['$rootScope', '$scope', 'myservice',
    function ($rootScope, $scope, myservice) {
      $scope.myservice = myservice;
    }]);

testModule
    .service('myservice', function() {
      this.xxx = "yyy";
    });

这篇关于我怎样才能从一个控制器的一些数据传递给另一个对等控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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