我的目标是将一些数据从角度控制器发送到另一个控制器。
这是必须发送数据的控制器:
myApp.controller('MapCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.loadData = function () {
$http.get('/map/GetListDB').success(function (data, status, headers, config) {
//Logic here is working fine, it creates a table named "ExcelCols" which is a table of strings
$scope.$broadcast("SET_EXCEL_TITLES", $scope.ExcelCols);
})
}
}]);
这是第二个控制器
myApp.controller('ExcelViewCtrl', ['$scope', '$http', function($scope, $http) {
$scope.$on("SET_EXCEL_TITLES", function (event, excelCols) {
//this event is never fired
$scope.ExcelCols = excelCols;
});
}]);
我的观点是这样设计的:
<body ng-app="myApp">
<div ng-controller="MapCtrl">
//everything OK here
</div>
<div ng-controller="ExcelViewCtrl">
<table>
<thead>
<tr>
<th ng-repeat="col in ExcelCols">{{col}}</th>
</tr>
</thead>
</table>
</div>
</body>
根据控制器的结构,w.r.t到$broadcast
的消息将被路由。
根据文件
向下向所有子作用域(及其children)通知侦听器上已注册的ng.$rootScope.Scope#$。
这意味着发送广播的控制器应该在子控制器html的父html上定义。
根据您的html结构,使用$rootScope.$broadcast
。将$rootScope
注入到MapCtrl
中,并在其上调用$broadcast
方法。
我认为$scope.$broadcast
需要使用$rootScope
。参见JSFiddle 中的好例子
以下是AngularJS–控制器之间的通信示例:
使用共享服务进行通信的示例。
http://jsfiddle.net/simpulton/XqDxG/
"ControllerZero" Broadcast to "ControllerOne" and "ControllerTwo"
和视频教程
http://onehungrymind.com/angularjs-communicating-between-controllers/
另一个选项是使用$rootScope列出到事件,并使用local$scope发出它。我创建了这个plnkr来测试它http://plnkr.co/edit/LJECQZ?p=info
var app = angular.module('plunker', []);
app.controller('Ctl1', function($scope, $rootScope) {
$scope.name = 'World';
$rootScope.$on('changeValueInCtl1', function(event, value) {
$scope.name = 'New Value from Ctl2 is: ' + value;
});
});
app.controller('Ctl2', function($scope) {
$scope.changeValue = function() {
$scope.$emit('changeValueInCtl1', 'Control 2 value');
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="Ctl1">
<p>Hello {{name}}!</p>
</div>
<div ng-controller="Ctl2">
<button ng-click="changeValue()">Change Value</button>
</div>
</body>
</html>
唯一的缺点是$rootScope将侦听,并且必须显式地调用$destroy。