[英]How can I send a message from one controller to another in AngularJS?
I have the following set up: 我有以下设置:
stApp.controller('AdminTableController', ['$rootScope', '$scope', 'gridService',
function ($rootScope, $scope, gridService) {
$scope.$watch('tableData.$pristine', function (newValue) {
$rootScope.broadcast("tableDataUpdated", {
state: page.$pristine
});
});
}])
stApp.controller('AdminGridController', ['$rootScope', '$scope', 'gridService',
function ($rootScope, $scope, gridService) {
$rootScope.on("tableDataUpdated", function (args) {
//args.state would have the state.
alert(args.state);
});
}])
When I run this code I am getting a message: 当我运行此代码时,我收到一条消息:
Object #<Object> has no method 'on'
Note that I tried this with both $rootScope.on and $scope.on 请注意,我尝试使用$ rootScope.on和$ scope.on
You must have meant $broadcast
and $on
(rather than broadcast
and on
), that is: 你必须意味着$broadcast
和$on
(而不是broadcast
和on
),即:
$rootScope.$broadcast("tableDataUpdated", { state: page.$pristine });
// ...
$rootScope.$on("tableDataUpdated", function (args) {
// ...
It's worth noting that $broadcast
is used to delegate events to child or sibling scopes, whereas $emit
will bubble events upwards to the scope's parents, hence; 值得注意的是, $broadcast
用于将事件委托给子节点或兄弟节点范围,而$emit
会将事件向上传递给范围的父节点,因此;
When choosing $broadcast
(and not $emit
), one should either inject the root scope for tying the $on
(as you nicely did ) or call $on
on the receiver's isolated scope, be it a child scope of the dispatcher. 当选择$broadcast
(而不是$emit
),你要么注入根范围为搭售$on
(为你做了很好),或致电$on
接收器上的隔离范围,无论是调度员的一个子范围。
See this post for elaboration on $emit
and $broadcast
. 有关$emit
和$broadcast
详细信息 ,请参阅此文章 。
If the event listener is in a child scope : $scope.$broadcast('MyEvent', args);
如果事件监听器在子范围内 : $scope.$broadcast('MyEvent', args);
If the event listener is in a parent scope : $scope.$emit('MyEvent', args);
如果事件监听器位于父作用域中 : $scope.$emit('MyEvent', args);
You could avoid any confusion by using $broadcast on $rootScope, since $rootScope is the parent of all scopes in an Angular application: $rootScope.$broadcast('MyEvent', args);
你可以通过在$ rootScope上使用$ broadcast来避免任何混淆,因为$ rootScope是Angular应用程序中所有作用域的父级: $rootScope.$broadcast('MyEvent', args);
Whether you use $emit or $broadcast, the receiving controller listens with $scope.$on('MyEvent', function() {});
无论你使用$ emit还是$ broadcast,接收控制器都会监听$scope.$on('MyEvent', function() {});
$rootScope.on("tableDataUpdated", function (args) {
//args.state would have the state.
alert(args.state);
});
should be 应该
$rootScope.$on("tableDataUpdated", function (args) {
//args.state would have the state.
alert(args.state);
});
$scope.$emit('MyEvent', args);
从第一个控制器,并在第二个控制器接收:
$scope.$on('MyEvent', function() {});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.