控制器之间的正确通信方式是什么?
我目前正在使用一个可怕的软糖涉及窗口:
function StockSubgroupCtrl($scope, $http) {
$scope.subgroups = [];
$scope.handleSubgroupsLoaded = function(data, status) {
$scope.subgroups = data;
}
$scope.fetch = function(prod_grp) {
$http.get('/api/stock/groups/' + prod_grp + '/subgroups/').success($scope.handleSubgroupsLoaded);
}
window.fetchStockSubgroups = $scope.fetch;
}
function StockGroupCtrl($scope, $http) {
...
$scope.select = function(prod_grp) {
$scope.selectedGroup = prod_grp;
window.fetchStockSubgroups(prod_grp);
}
}
这是一个快速而肮脏的方法。
// Add $injector as a parameter for your controller
function myAngularController($scope,$injector){
$scope.sendorders = function(){
// now you can use $injector to get the
// handle of $rootScope and broadcast to all
$injector.get('$rootScope').$broadcast('sinkallships');
};
}
下面是一个可以添加到任何兄弟控制器中的示例函数:
$scope.$on('sinkallships', function() {
alert('Sink that ship!');
});
当然这是你的HTML:
<button ngclick="sendorders()">Sink Enemy Ships</button>
上面的答案是@zumalifeguard提到的一个Angular问题,这个问题已经不存在了(至少在>1.2.16版本和“可能更早”)。但我读了所有这些答案,却没有一个实际的解决方案。
在我看来,现在的答案应该是
使用$rootScope中的$broadcast
从需要了解事件的本地$作用域使用$on进行监听
所以要发表
// EXAMPLE PUBLISHER
angular.module('test').controller('CtrlPublish', ['$rootScope', '$scope',
function ($rootScope, $scope) {
$rootScope.$broadcast('topic', 'message');
}]);
和订阅
// EXAMPLE SUBSCRIBER
angular.module('test').controller('ctrlSubscribe', ['$scope',
function ($scope) {
$scope.$on('topic', function (event, arg) {
$scope.receiver = 'got your ' + arg;
});
}]);
普伦克斯
常规$scope语法(如上所示)
new Controller As语法
如果您在本地$作用域上注册了侦听器,当关联的控制器被删除时,它将被$destroy自身自动销毁。
从angular 1.5开始,它的基于组件的开发重点。组件交互的推荐方式是使用'require'属性和通过属性绑定(输入/输出)。
一个组件需要另一个组件(例如根组件),并获得对它的控制器的引用:
angular.module('app').component('book', {
bindings: {},
require: {api: '^app'},
template: 'Product page of the book: ES6 - The Essentials',
controller: controller
});
然后你可以在你的子组件中使用根组件的方法:
$ctrl.api.addWatchedBook('ES6 - The Essentials');
这是根组件控制器函数:
function addWatchedBook(bookName){
booksWatched.push(bookName);
}
下面是一个完整的体系结构概述:组件通信