如何将一些数据从一个控制器传递到另一个对等控制器 [英] How can I pass some data from one controller to another peer controller
问题描述
我有以下两个对等控制器.这些没有父级:
<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屋!