使用$ scope。$ emit和$ scope。$ on [英] Working with $scope.$emit and $scope.$on
问题描述
如何使用将$ code> $ scope
对象从一个控制器发送到另一个控制器。$ emit 和。$ on
方法?
How can I send my $scope
object from one controller to another using .$emit
and .$on
methods?
function firstCtrl($scope) {
$scope.$emit('someEvent', [1,2,3]);
}
function secondCtrl($scope) {
$scope.$on('someEvent', function(mass) { console.log(mass); });
}
它不按我认为应该的方式工作。如何 $ emit
和 $
工作?
It doesn't work the way I think it should. How do $emit
and $on
work?
推荐答案
首先,父子范围关系确实很重要。您有两种可能会发出一些事件:
First of all, parent-child scope relation does matter. You have two possibilities to emit some event:
-
$ broadcast
- 发送事件向下到所有子范围, -
$ emit
- 通过范围层次结构向上调度事件。
$broadcast
-- dispatches the event downwards to all child scopes,$emit
-- dispatches the event upwards through the scope hierarchy.
我对你的控制器(范围)关系一无所知,但有几种选择:
I don't know anything about your controllers (scopes) relation, but there are several options:
-
如果
firstCtrl
的范围是secondCtrl
范围的父级,则代码应
通过在$ code> firstCtrl$ broadcast
中替换$ emit
来工作:
If scope of
firstCtrl
is parent of thesecondCtrl
scope, your code should work by replacing$emit
by$broadcast
infirstCtrl
:
function firstCtrl($scope)
{
$scope.$broadcast('someEvent', [1,2,3]);
}
function secondCtrl($scope)
{
$scope.$on('someEvent', function(event, mass) { console.log(mass); });
}
如果你的范围之间没有父子关系你
可以将 $ rootScope
注入控制器并将事件
广播到所有子范围(即 secondCtrl
)。
In case there is no parent-child relation between your scopes you
can inject $rootScope
into the controller and broadcast the event
to all child scopes (i.e. also secondCtrl
).
function firstCtrl($rootScope)
{
$rootScope.$broadcast('someEvent', [1,2,3]);
}
最后,当您需要从子控制器$调度事件时b $ b到范围向上你可以使用 $ scope。$ emit
。如果 firstCtrl
的范围是 secondCtrl
范围的父级:
Finally, when you need to dispatch the event from child controller
to scopes upwards you can use $scope.$emit
. If scope of firstCtrl
is parent of the secondCtrl
scope:
function firstCtrl($scope)
{
$scope.$on('someEvent', function(event, data) { console.log(data); });
}
function secondCtrl($scope)
{
$scope.$emit('someEvent', [1,2,3]);
}
这篇关于使用$ scope。$ emit和$ scope。$ on的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!