[英]Angular, broadcast not working
我的目標是將一些數據從角度控制器發送到另一個。
這是必須發送數據的控制器:
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>
根據控制器的結構,將路由到$broadcast
消息。
根據文件
將事件名稱向下調度到所有子范圍(及其子級),通知已注冊的ng。$ rootScope.Scope#$ on listeners。
這意味着發送廣播的控制器應該在子控制器html的父html上定義。
根據您的html結構,使用$rootScope.$broadcast
。 將$rootScope
注入MapCtrl
並在其上調用$broadcast
方法。
我認為你需要使用$rootScope
而不是$scope.$broadcast
。 在JSFiddle中查看好的示例
以下是AngularJS的示例 - 在控制器之間進行通信:
使用共享服務進行通信的示例。
http://jsfiddle.net/simpulton/XqDxG/
"ControllerZero" Broadcast to "ControllerOne" and "ControllerTwo"
和視頻教程
http://onehungrymind.com/angularjs-communicating-between-controllers/
另一個選擇是使用$ rootScope列出事件和本地$ 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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.