如何将一些数据从一个控制器传递到另一个对等控制器 [英] How can I pass some data from one controller to another peer controller

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

问题描述

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

<div data-ng-controller="Controller2">xxx 的值为:{{ xxx }}

angular.module('测试').controller('QuestionsStatusController1',['$rootScope', '$scope'函数($rootScope,$scope){//如何在属于 Controller2 的 HTML 中设置 xxx 的值}]);angular.module('测试').controller('QuestionsStatusController2',['$rootScope', '$scope',函数($rootScope,$scope){}]);

在控制器 1 中,我想更新由控制器 2 控制的 HTML 中变量 xxx 的值.有没有办法做到这一点?

解决方案

绝对使用服务在控制器之间共享数据,这里是一个工作示例.$broadcast 不是要走的路,当有更合适的方法时,您应该避免使用事件系统.使用服务"、值"或常量"(用于全局常量).

http://plnkr.co/edit/ETWU7d0O8Kaz6qpFP5Hp

这是一个带有输入的示例,因此您可以在页面上看到数据镜像:http://plnkr.co/edit/DbBp60AgfbmGpgvwtnpU

var testModule = angular.module('testmodule', []);测试模块.controller('QuestionsStatusController1',['$rootScope', '$scope', 'myservice',功能($rootScope,$scope,myservice){$scope.myservice = myservice;}]);测试模块.controller('QuestionsStatusController2',['$rootScope', '$scope', 'myservice',功能($rootScope,$scope,myservice){$scope.myservice = myservice;}]);测试模块.service('myservice', function() {this.xxx = "yyy";});

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

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

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天全站免登陆