How can I send my $scope
object from one controller to another using .$emit
and .$on
methods?
如何将$scope对象从一个控制器发送到另一个使用。$emit和。$on方法?
function firstCtrl($scope) {
$scope.$emit('someEvent', [1,2,3]);
}
function secondCtrl($scope) {
$scope.$on('someEvent', function(mass) { console.log(mass); });
}
It doesn't work the way I think it should. How do $emit
and $on
work?
这不是我认为应该的方式。$如何排放和$on work?
13 个解决方案
#1
1465
First of all, parent-child scope relation does matter. You have two possibilities to emit some event:
首先,父子范围关系很重要。你有两种可能会发射一些事件:
-
$broadcast
-- dispatches the event downwards to all child scopes, - $broadcast——将事件向下发送到所有子作用域,
-
$emit
-- dispatches the event upwards through the scope hierarchy. - $emit——通过范围层次结构向上发送事件。
I don't know anything about your controllers (scopes) relation, but there are several options:
我对你们的控制器(作用域)关系一无所知,但是有几个选项:
-
If scope of
firstCtrl
is parent of thesecondCtrl
scope, your code should work by replacing$emit
by$broadcast
infirstCtrl
:如果firstCtrl的作用域是secondCtrl作用域的父元素,那么您的代码应该通过在firstCtrl中使用$broadcast替换$emit来工作:
function firstCtrl($scope) { $scope.$broadcast('someEvent', [1,2,3]); } function secondCtrl($scope) { $scope.$on('someEvent', function(event, mass) { console.log(mass); }); }
-
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. alsosecondCtrl
).如果您的作用域之间没有父子关系,您可以向控制器中注入$rootScope,并将事件广播到所有子范围(也就是secondCtrl)。
function firstCtrl($rootScope) { $rootScope.$broadcast('someEvent', [1,2,3]); }
-
Finally, when you need to dispatch the event from child controller to scopes upwards you can use
$scope.$emit
. If scope offirstCtrl
is parent of thesecondCtrl
scope:最后,当您需要将事件从子控制器分派到向上的作用域时,您可以使用$scope.$emit。如果firstCtrl的作用域是secondCtrl作用域的父元素:
function firstCtrl($scope) { $scope.$on('someEvent', function(event, data) { console.log(data); }); } function secondCtrl($scope) { $scope.$emit('someEvent', [1,2,3]); }
#2
139
I would additionally suggest a 4th option as a better alternative to the proposed options by @zbynour.
我还会建议第四个选项,作为@zbynour提议的选项的更好的替代方案。
Use $rootScope.$emit
rather than $rootScope.$broadcast
regardless of the relationship between trasmitting and receiving controller. That way, the event remains within the set of $rootScope.$$listeners
whereas with $rootScope.$broadcast
the event propagates to all children scopes, most of which will probably not be listeners of that event anyway. And of course in the receiving controller's end you just use $rootScope.$on
.
使用rootScope美元。发出,而不是rootScope美元。$broadcast,不考虑授予和接收控制之间的关系。这样,事件仍然在$rootScope的集合中。听众而rootScope美元美元。$broadcast事件传播到所有子作用域,其中大多数可能都不是该事件的监听器。当然在接收控制器的最后你只需要使用$rootScope, $on。
For this option you must remember to destroy the controller's rootScope listeners:
对于此选项,您必须记住销毁控制器的rootScope侦听器:
var unbindEventHandler = $rootScope.$on('myEvent', myHandler);
$scope.$on('$destroy', function () {
unbindEventHandler();
});
#3
107
How can I send my $scope object from one controller to another using .$emit and .$on methods?
如何将$scope对象从一个控制器发送到另一个使用。$emit和。$on方法?
You can send any object you want within the hierarchy of your app, including $scope.
您可以在应用程序的层次结构中发送任何您想要的对象,包括$scope。
Here is a quick idea about how broadcast and emit work.
这里有一个关于广播和发射工作的快速想法。
Notice the nodes below; all nested within node 3. You use broadcast and emit when you have this scenario.
请注意下面的节点;都嵌套在节点3中。当您有这个场景时,您使用广播和发送。
Note: The number of each node in this example is arbitrary; it could easily be the number one; the number two; or even the number 1,348. Each number is just an identifier for this example. The point of this example is to show nesting of Angular controllers/directives.
注意:本例中的每个节点的数目是任意的;它很容易成为第一;2号;甚至是1348。每个数字都是这个例子的标识符。本例的目的是展示角控制器/指令的嵌套。
3
------------
| |
----- ------
1 | 2 |
--- --- --- ---
| | | | | | | |
Check out this tree. How do you answer the following questions?
看看这棵树。你如何回答下列问题?
Note: There are other ways to answer these questions, but here we'll discuss broadcast and emit. Also, when reading below text assume each number has it's own file (directive, controller) e.x. one.js, two.js, three.js.
注意:有其他方法可以回答这些问题,但是这里我们将讨论广播和发射。另外,当阅读下面的文本时,假设每个数字都有自己的文件(指令、控制器)。js,两个。js,three.js。
How does node 1 speak to node 3?
节点1如何与节点3对话?
In file one.js
在文件one.js
scope.$emit('messageOne', someValue(s));
In file three.js - the uppermost node to all children nodes needed to communicate.
在三个文件。js -所有子节点的最上面节点需要进行通信。
scope.$on('messageOne', someValue(s));
How does node 2 speak to node 3?
节点2如何与节点3对话?
In file two.js
在文件two.js
scope.$emit('messageTwo', someValue(s));
In file three.js - the uppermost node to all children nodes needed to communicate.
在三个文件。js -所有子节点的最上面节点需要进行通信。
scope.$on('messageTwo', someValue(s));
How does node 3 speak to node 1 and/or node 2?
节点3如何与节点1和/或节点2对话?
In file three.js - the uppermost node to all children nodes needed to communicate.
在三个文件。js -所有子节点的最上面节点需要进行通信。
scope.$broadcast('messageThree', someValue(s));
In file one.js && two.js whichever file you want to catch the message or both.
在文件。js & &两个。你想要捕获消息的任何文件,或者两者都要。
scope.$on('messageThree', someValue(s));
How does node 2 speak to node 1?
节点2如何与节点1对话?
In file two.js
在文件two.js
scope.$emit('messageTwo', someValue(s));
In file three.js - the uppermost node to all children nodes needed to communicate.
在三个文件。js -所有子节点的最上面节点需要进行通信。
scope.$on('messageTwo', function( event, data ){
scope.$broadcast( 'messageTwo', data );
});
In file one.js
在文件one.js
scope.$on('messageTwo', someValue(s));
HOWEVER
然而
When you have all these nested child nodes trying to communicate like this, you will quickly see many $on's, $broadcast's, and $emit's.
当所有这些嵌套的子节点尝试像这样进行通信时,您将很快看到许多$on、$broadcast和$emit。
Here is what I like to do.
这是我喜欢做的。
In the uppermost PARENT NODE ( 3 in this case... ), which may be your parent controller...
在最上面的父节点(在本例中为3),可能是你的父控制器…
So, in file three.js
因此,在文件three.js
scope.$on('pushChangesToAllNodes', function( event, message ){
scope.$broadcast( message.name, message.data );
});
Now in any of the child nodes you only need to $emit the message or catch it using $on.
现在,在任何子节点中,您只需要$发送消息或使用$on捕获消息。
NOTE: It is normally quite easy to cross talk in one nested path without using $emit, $broadcast, or $on, which means most use cases are for when you are trying to get node 1 to communicate with node 2 or vice versa.
注意:通常在一个嵌套路径中不使用$emit、$broadcast或$on进行交叉对话是非常容易的,这意味着当您试图让节点1与节点2通信时,大多数用例都适用,反之亦然。
How does node 2 speak to node 1?
节点2如何与节点1对话?
In file two.js
在文件two.js
scope.$emit('pushChangesToAllNodes', sendNewChanges());
function sendNewChanges(){ // for some event.
return { name: 'talkToOne', data: [1,2,3] };
}
In file three.js - the uppermost node to all children nodes needed to communicate.
在三个文件。js -所有子节点的最上面节点需要进行通信。
We already handled this one remember?
我们已经处理过这个了,记得吗?
In file one.js
在文件one.js
scope.$on('talkToOne', function( event, arrayOfNumbers ){
arrayOfNumbers.forEach(function(number){
console.log(number);
});
});
You will still need to use $on with each specific value you want to catch, but now you can create whatever you like in any of the nodes without having to worry about how to get the message across the parent node gap as we catch and broadcast the generic pushChangesToAllNodes.
你仍然需要用美元与每个特定值你想抓住,但是现在你可以创造任何你喜欢的节点无需担心如何将消息在父节点的差距我们抓住和广播通用pushChangesToAllNodes。
Hope this helps...
希望这有助于……
#4
35
To send $scope object
from one controller to another, I will discuss about $rootScope.$broadcast
and $rootScope.$emit
here as they are used most.
要将$scope对象从一个控制器发送到另一个控制器,我将讨论$rootScope。广播和rootScope美元。$emit在这里是最常用的。
Case 1:
案例1:
$rootScope.$broadcast:-
rootScope。广播:美元-
$rootScope.$broadcast('myEvent',$scope.data);//Here `myEvent` is event name
$rootScope.$on('myEvent', function(event, data) {} //listener on `myEvent` event
$rootScope
listener are not destroyed automatically. You need to destroy it using $destroy
. It is better to use $scope.$on
as listeners on $scope
are destroyed automatically i.e. as soon as $scope is destroyed.
$rootScope侦听器不会自动销毁。你需要用$destroy摧毁它。最好使用$scope。$on作为$scope的侦听器被自动销毁,即一旦$scope被销毁。
$scope.$on('myEvent', function(event, data) {}
Or,
或者,
var customeEventListener = $rootScope.$on('myEvent', function(event, data) {
}
$scope.$on('$destroy', function() {
customeEventListener();
});
Case 2:
案例2:
$rootScope.$emit:
rootScope。美元发出:
$rootScope.$emit('myEvent',$scope.data);
$rootScope.$on('myEvent', function(event, data) {}//$scope.$on not works
The major difference in $emit and $broadcast is that $rootScope.$emit event must be listened using $rootScope.$on, because the emitted event never comes down through the scope tree..
In this case also you must destroy the listener as in the case of $broadcast.
$emit和$broadcast的主要差异在于$rootScope。$emit事件必须使用$rootScope来侦听。$on,因为发出的事件永远不会通过范围树下降。在这种情况下,您还必须像在$broadcast中那样销毁侦听器。
Edit:
编辑:
I prefer not to use
$rootScope.$broadcast + $scope.$on
but use$rootScope.$emit+ $rootScope.$on
. The$rootScope.$broadcast + $scope.$on
combo can cause serious performance problems. That is because the event will bubble down through all scopes.我不喜欢使用$rootScope。广播+美元范围。但使用rootScope美元美元。发出+ rootScope。美元美元。rootScope美元。广播+美元范围。$on combo会导致严重的性能问题。这是因为事件将在所有范围内冒泡。
Edit 2:
编辑2:
The issue addressed in this answer have been resolved in angular.js version 1.2.7. $broadcast now avoids bubbling over unregistered scopes and runs just as fast as $emit.
在这个答案中所讨论的问题已经用角来解决了。1.2.7。编写js版本$broadcast现在避免了在未注册的作用域上冒泡,并且运行速度和$emit一样快。
#5
10
You must use $rootScope to send and capture events between controllers in same app. Inject $rootScope dependency to your controllers. Here is a working example.
必须使用$rootScope在同一应用程序中的控制器之间发送和捕获事件。向控制器注入$rootScope依赖项。这里有一个工作示例。
app.controller('firstCtrl', function($scope, $rootScope) {
function firstCtrl($scope) {
{
$rootScope.$emit('someEvent', [1,2,3]);
}
}
app.controller('secondCtrl', function($scope, $rootScope) {
function secondCtrl($scope)
{
$rootScope.$on('someEvent', function(event, data) { console.log(data); });
}
}
Events linked into $scope object just work in the owner controller. Communication between controllers is done via $rootScope or Services.
连接到$scope对象的事件只在所有者控制器中工作。控制器之间的通信通过$rootScope或服务来完成。
#6
6
You can call a service from your controller that returns a promise and then use it in your controller. And further use $emit
or $broadcast
to inform other controllers about it. In my case, I had to make http calls through my service, so I did something like this :
您可以从您的控制器调用服务,该服务返回一个承诺,然后在您的控制器中使用它。并进一步使用$emit或$广播通知其他控制器。在我的例子中,我必须通过我的服务进行http调用,所以我做了这样的事情:
function ParentController($scope, testService) {
testService.getList()
.then(function(data) {
$scope.list = testService.list;
})
.finally(function() {
$scope.$emit('listFetched');
})
function ChildController($scope, testService) {
$scope.$on('listFetched', function(event, data) {
// use the data accordingly
})
}
and my service looks like this
我的服务是这样的
app.service('testService', ['$http', function($http) {
this.list = [];
this.getList = function() {
return $http.get(someUrl)
.then(function(response) {
if (typeof response.data === 'object') {
list = response.data.results;
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
}, function(response) {
// something went wrong
return $q.reject(response.data);
});
}
}])
#7
3
This is my function:
这是我的功能:
$rootScope.$emit('setTitle', newVal.full_name);
$rootScope.$on('setTitle', function(event, title) {
if (scope.item)
scope.item.name = title;
else
scope.item = {name: title};
});
#8
3
<!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('MyApp',[]);
app.controller('parentCtrl',function($scope){
$scope.$on('MyEvent',function(event,data){
$scope.myData = data;
});
});
app.controller('childCtrl',function($scope){
$scope.fireEvent = function(){
$scope.$emit('MyEvent','Any Data');
}
});
</script>
</head>
<body ng-app="MyApp">
<div ng-controller="parentCtrl" ng-model="myName">
{{myData}}
<div ng-controller="childCtrl">
<button ng-click="fireEvent()">Fire Event</button>
</div>
</div>
</body>
</html>
#9
2
I ended up adding an external EventEmitter library to project as a service and injecting it wherever I need. So I can "emit" and "on" anything anywhere without caring for scope inheritance. It is less trouble this way and certainly better performance. Also more readable to me.
最后,我将一个外部的EventEmitter库作为一个服务添加到项目中,并将其注入到我需要的任何地方。因此,我可以“释放”和“在”任何地方,而不关心范围继承。这样做麻烦少了,性能当然也更好了。对我来说也更容易读懂。
Wildcard support: EventEmitter2
通配符支持:EventEmitter2
Good performance: eventemitter3
良好的性能:eventemitter3
Other alternative: Drip
其他:滴
#10
2
Below code shows the two sub-controllers from where the events are dispatched upwards to parent controller (rootScope)
下面的代码显示了事件向上发送到父控制器(rootScope)的两个子控制器
<body ng-app="App">
<div ng-controller="parentCtrl">
<p>City : {{city}} </p>
<p> Address : {{address}} </p>
<div ng-controller="subCtrlOne">
<input type="text" ng-model="city" />
<button ng-click="getCity(city)">City !!!</button>
</div>
<div ng-controller="subCtrlTwo">
<input type="text" ng-model="address" />
<button ng-click="getAddrress(address)">Address !!!</button>
</div>
</div>
</body>
var App = angular.module('App', []);
// parent controller
App.controller('parentCtrl', parentCtrl);
parentCtrl.$inject = ["$scope"];
function parentCtrl($scope) {
$scope.$on('cityBoom', function(events, data) {
$scope.city = data;
});
$scope.$on('addrBoom', function(events, data) {
$scope.address = data;
});
}
// sub controller one
App.controller('subCtrlOne', subCtrlOne);
subCtrlOne.$inject = ['$scope'];
function subCtrlOne($scope) {
$scope.getCity = function(city) {
$scope.$emit('cityBoom', city);
}
}
// sub controller two
App.controller('subCtrlTwo', subCtrlTwo);
subCtrlTwo.$inject = ["$scope"];
function subCtrlTwo($scope) {
$scope.getAddrress = function(addr) {
$scope.$emit('addrBoom', addr);
}
}
http://jsfiddle.net/shushanthp/zp6v0rut/
http://jsfiddle.net/shushanthp/zp6v0rut/
#11
1
Scope(s) can be used to propagate, dispatch event to the scope children or parent.
作用域可以用于将事件传播、分派给作用域子或父对象。
$emit - propagates the event to parent. $broadcast - propagates the event to children. $on - method to listen the events, propagated by $emit and $broadcast.
$emit -传播该事件到父节点。$broadcast -将事件传播给孩子。$on -方法监听事件,由$emit和$broadcast传播。
example index.html:
index . html示例:
<div ng-app="appExample" ng-controller="EventCtrl">
Root(Parent) scope count: {{count}}
<div>
<button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
<button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button><br>
Childrent scope count: {{count}}
</div>
</div>
example app.js:
示例app.js:
angular.module('appExample', [])
.controller('EventCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.$on('MyEvent', function() {
$scope.count++;
});
}]);
Here u can test code: http://jsfiddle.net/zp6v0rut/41/
这里可以测试代码:http://jsfiddle.net/zp6v0rut/41/。
#12
0
According to the angularjs event docs the receiving end should be containing arguments with a structure like
根据angularjs事件文档,接收端应该包含具有类似结构的参数
@params
@params
-- {Object} event being the event object containing info on the event
- {Object}事件是包含事件信息的事件对象
-- {Object} args that are passed by the callee (Note that this can only be one so better to send in a dictionary object always)
——被被callee传递的{Object} args(注意,这只能是一种更好的方式,始终发送一个dictionary对象)
$scope.$on('fooEvent', function (event, args) { console.log(args) });
From your code
美元的范围。$on('fooEvent', function (event, args) {console.log(args)});从你的代码
Also if you are trying to get a shared piece of information to be available accross different controllers there is an another way to achieve that and that is angular services.Since the services are singletons information can be stored and fetched across controllers.Simply create getter and setter functions in that service, expose these functions, make global variables in the service and use them to store the info
另外,如果你想要获取共享的信息,并通过不同的控制器获得,还有另一种方法,那就是角化服务。由于服务是单例信息,所以可以跨控制器存储和获取信息。只需在该服务中创建getter和setter函数,公开这些函数,在服务中创建全局变量并使用它们存储信息
#13
0
The Easiest way :
最简单的方法:
HTML
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="sendData();"> Send Data </button>
</div>
JavaScript
JavaScript
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $rootScope) {
function sendData($scope) {
var arrayData = ['sam','rumona','cubby'];
$rootScope.$emit('someEvent', arrayData);
}
});
app.controller('yourCtrl', function($scope, $rootScope) {
$rootScope.$on('someEvent', function(event, data) {
console.log(data);
});
});
</script>
#1
1465
First of all, parent-child scope relation does matter. You have two possibilities to emit some event:
首先,父子范围关系很重要。你有两种可能会发射一些事件:
-
$broadcast
-- dispatches the event downwards to all child scopes, - $broadcast——将事件向下发送到所有子作用域,
-
$emit
-- dispatches the event upwards through the scope hierarchy. - $emit——通过范围层次结构向上发送事件。
I don't know anything about your controllers (scopes) relation, but there are several options:
我对你们的控制器(作用域)关系一无所知,但是有几个选项:
-
If scope of
firstCtrl
is parent of thesecondCtrl
scope, your code should work by replacing$emit
by$broadcast
infirstCtrl
:如果firstCtrl的作用域是secondCtrl作用域的父元素,那么您的代码应该通过在firstCtrl中使用$broadcast替换$emit来工作:
function firstCtrl($scope) { $scope.$broadcast('someEvent', [1,2,3]); } function secondCtrl($scope) { $scope.$on('someEvent', function(event, mass) { console.log(mass); }); }
-
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. alsosecondCtrl
).如果您的作用域之间没有父子关系,您可以向控制器中注入$rootScope,并将事件广播到所有子范围(也就是secondCtrl)。
function firstCtrl($rootScope) { $rootScope.$broadcast('someEvent', [1,2,3]); }
-
Finally, when you need to dispatch the event from child controller to scopes upwards you can use
$scope.$emit
. If scope offirstCtrl
is parent of thesecondCtrl
scope:最后,当您需要将事件从子控制器分派到向上的作用域时,您可以使用$scope.$emit。如果firstCtrl的作用域是secondCtrl作用域的父元素:
function firstCtrl($scope) { $scope.$on('someEvent', function(event, data) { console.log(data); }); } function secondCtrl($scope) { $scope.$emit('someEvent', [1,2,3]); }
#2
139
I would additionally suggest a 4th option as a better alternative to the proposed options by @zbynour.
我还会建议第四个选项,作为@zbynour提议的选项的更好的替代方案。
Use $rootScope.$emit
rather than $rootScope.$broadcast
regardless of the relationship between trasmitting and receiving controller. That way, the event remains within the set of $rootScope.$$listeners
whereas with $rootScope.$broadcast
the event propagates to all children scopes, most of which will probably not be listeners of that event anyway. And of course in the receiving controller's end you just use $rootScope.$on
.
使用rootScope美元。发出,而不是rootScope美元。$broadcast,不考虑授予和接收控制之间的关系。这样,事件仍然在$rootScope的集合中。听众而rootScope美元美元。$broadcast事件传播到所有子作用域,其中大多数可能都不是该事件的监听器。当然在接收控制器的最后你只需要使用$rootScope, $on。
For this option you must remember to destroy the controller's rootScope listeners:
对于此选项,您必须记住销毁控制器的rootScope侦听器:
var unbindEventHandler = $rootScope.$on('myEvent', myHandler);
$scope.$on('$destroy', function () {
unbindEventHandler();
});
#3
107
How can I send my $scope object from one controller to another using .$emit and .$on methods?
如何将$scope对象从一个控制器发送到另一个使用。$emit和。$on方法?
You can send any object you want within the hierarchy of your app, including $scope.
您可以在应用程序的层次结构中发送任何您想要的对象,包括$scope。
Here is a quick idea about how broadcast and emit work.
这里有一个关于广播和发射工作的快速想法。
Notice the nodes below; all nested within node 3. You use broadcast and emit when you have this scenario.
请注意下面的节点;都嵌套在节点3中。当您有这个场景时,您使用广播和发送。
Note: The number of each node in this example is arbitrary; it could easily be the number one; the number two; or even the number 1,348. Each number is just an identifier for this example. The point of this example is to show nesting of Angular controllers/directives.
注意:本例中的每个节点的数目是任意的;它很容易成为第一;2号;甚至是1348。每个数字都是这个例子的标识符。本例的目的是展示角控制器/指令的嵌套。
3
------------
| |
----- ------
1 | 2 |
--- --- --- ---
| | | | | | | |
Check out this tree. How do you answer the following questions?
看看这棵树。你如何回答下列问题?
Note: There are other ways to answer these questions, but here we'll discuss broadcast and emit. Also, when reading below text assume each number has it's own file (directive, controller) e.x. one.js, two.js, three.js.
注意:有其他方法可以回答这些问题,但是这里我们将讨论广播和发射。另外,当阅读下面的文本时,假设每个数字都有自己的文件(指令、控制器)。js,两个。js,three.js。
How does node 1 speak to node 3?
节点1如何与节点3对话?
In file one.js
在文件one.js
scope.$emit('messageOne', someValue(s));
In file three.js - the uppermost node to all children nodes needed to communicate.
在三个文件。js -所有子节点的最上面节点需要进行通信。
scope.$on('messageOne', someValue(s));
How does node 2 speak to node 3?
节点2如何与节点3对话?
In file two.js
在文件two.js
scope.$emit('messageTwo', someValue(s));
In file three.js - the uppermost node to all children nodes needed to communicate.
在三个文件。js -所有子节点的最上面节点需要进行通信。
scope.$on('messageTwo', someValue(s));
How does node 3 speak to node 1 and/or node 2?
节点3如何与节点1和/或节点2对话?
In file three.js - the uppermost node to all children nodes needed to communicate.
在三个文件。js -所有子节点的最上面节点需要进行通信。
scope.$broadcast('messageThree', someValue(s));
In file one.js && two.js whichever file you want to catch the message or both.
在文件。js & &两个。你想要捕获消息的任何文件,或者两者都要。
scope.$on('messageThree', someValue(s));
How does node 2 speak to node 1?
节点2如何与节点1对话?
In file two.js
在文件two.js
scope.$emit('messageTwo', someValue(s));
In file three.js - the uppermost node to all children nodes needed to communicate.
在三个文件。js -所有子节点的最上面节点需要进行通信。
scope.$on('messageTwo', function( event, data ){
scope.$broadcast( 'messageTwo', data );
});
In file one.js
在文件one.js
scope.$on('messageTwo', someValue(s));
HOWEVER
然而
When you have all these nested child nodes trying to communicate like this, you will quickly see many $on's, $broadcast's, and $emit's.
当所有这些嵌套的子节点尝试像这样进行通信时,您将很快看到许多$on、$broadcast和$emit。
Here is what I like to do.
这是我喜欢做的。
In the uppermost PARENT NODE ( 3 in this case... ), which may be your parent controller...
在最上面的父节点(在本例中为3),可能是你的父控制器…
So, in file three.js
因此,在文件three.js
scope.$on('pushChangesToAllNodes', function( event, message ){
scope.$broadcast( message.name, message.data );
});
Now in any of the child nodes you only need to $emit the message or catch it using $on.
现在,在任何子节点中,您只需要$发送消息或使用$on捕获消息。
NOTE: It is normally quite easy to cross talk in one nested path without using $emit, $broadcast, or $on, which means most use cases are for when you are trying to get node 1 to communicate with node 2 or vice versa.
注意:通常在一个嵌套路径中不使用$emit、$broadcast或$on进行交叉对话是非常容易的,这意味着当您试图让节点1与节点2通信时,大多数用例都适用,反之亦然。
How does node 2 speak to node 1?
节点2如何与节点1对话?
In file two.js
在文件two.js
scope.$emit('pushChangesToAllNodes', sendNewChanges());
function sendNewChanges(){ // for some event.
return { name: 'talkToOne', data: [1,2,3] };
}
In file three.js - the uppermost node to all children nodes needed to communicate.
在三个文件。js -所有子节点的最上面节点需要进行通信。
We already handled this one remember?
我们已经处理过这个了,记得吗?
In file one.js
在文件one.js
scope.$on('talkToOne', function( event, arrayOfNumbers ){
arrayOfNumbers.forEach(function(number){
console.log(number);
});
});
You will still need to use $on with each specific value you want to catch, but now you can create whatever you like in any of the nodes without having to worry about how to get the message across the parent node gap as we catch and broadcast the generic pushChangesToAllNodes.
你仍然需要用美元与每个特定值你想抓住,但是现在你可以创造任何你喜欢的节点无需担心如何将消息在父节点的差距我们抓住和广播通用pushChangesToAllNodes。
Hope this helps...
希望这有助于……
#4
35
To send $scope object
from one controller to another, I will discuss about $rootScope.$broadcast
and $rootScope.$emit
here as they are used most.
要将$scope对象从一个控制器发送到另一个控制器,我将讨论$rootScope。广播和rootScope美元。$emit在这里是最常用的。
Case 1:
案例1:
$rootScope.$broadcast:-
rootScope。广播:美元-
$rootScope.$broadcast('myEvent',$scope.data);//Here `myEvent` is event name
$rootScope.$on('myEvent', function(event, data) {} //listener on `myEvent` event
$rootScope
listener are not destroyed automatically. You need to destroy it using $destroy
. It is better to use $scope.$on
as listeners on $scope
are destroyed automatically i.e. as soon as $scope is destroyed.
$rootScope侦听器不会自动销毁。你需要用$destroy摧毁它。最好使用$scope。$on作为$scope的侦听器被自动销毁,即一旦$scope被销毁。
$scope.$on('myEvent', function(event, data) {}
Or,
或者,
var customeEventListener = $rootScope.$on('myEvent', function(event, data) {
}
$scope.$on('$destroy', function() {
customeEventListener();
});
Case 2:
案例2:
$rootScope.$emit:
rootScope。美元发出:
$rootScope.$emit('myEvent',$scope.data);
$rootScope.$on('myEvent', function(event, data) {}//$scope.$on not works
The major difference in $emit and $broadcast is that $rootScope.$emit event must be listened using $rootScope.$on, because the emitted event never comes down through the scope tree..
In this case also you must destroy the listener as in the case of $broadcast.
$emit和$broadcast的主要差异在于$rootScope。$emit事件必须使用$rootScope来侦听。$on,因为发出的事件永远不会通过范围树下降。在这种情况下,您还必须像在$broadcast中那样销毁侦听器。
Edit:
编辑:
I prefer not to use
$rootScope.$broadcast + $scope.$on
but use$rootScope.$emit+ $rootScope.$on
. The$rootScope.$broadcast + $scope.$on
combo can cause serious performance problems. That is because the event will bubble down through all scopes.我不喜欢使用$rootScope。广播+美元范围。但使用rootScope美元美元。发出+ rootScope。美元美元。rootScope美元。广播+美元范围。$on combo会导致严重的性能问题。这是因为事件将在所有范围内冒泡。
Edit 2:
编辑2:
The issue addressed in this answer have been resolved in angular.js version 1.2.7. $broadcast now avoids bubbling over unregistered scopes and runs just as fast as $emit.
在这个答案中所讨论的问题已经用角来解决了。1.2.7。编写js版本$broadcast现在避免了在未注册的作用域上冒泡,并且运行速度和$emit一样快。
#5
10
You must use $rootScope to send and capture events between controllers in same app. Inject $rootScope dependency to your controllers. Here is a working example.
必须使用$rootScope在同一应用程序中的控制器之间发送和捕获事件。向控制器注入$rootScope依赖项。这里有一个工作示例。
app.controller('firstCtrl', function($scope, $rootScope) {
function firstCtrl($scope) {
{
$rootScope.$emit('someEvent', [1,2,3]);
}
}
app.controller('secondCtrl', function($scope, $rootScope) {
function secondCtrl($scope)
{
$rootScope.$on('someEvent', function(event, data) { console.log(data); });
}
}
Events linked into $scope object just work in the owner controller. Communication between controllers is done via $rootScope or Services.
连接到$scope对象的事件只在所有者控制器中工作。控制器之间的通信通过$rootScope或服务来完成。
#6
6
You can call a service from your controller that returns a promise and then use it in your controller. And further use $emit
or $broadcast
to inform other controllers about it. In my case, I had to make http calls through my service, so I did something like this :
您可以从您的控制器调用服务,该服务返回一个承诺,然后在您的控制器中使用它。并进一步使用$emit或$广播通知其他控制器。在我的例子中,我必须通过我的服务进行http调用,所以我做了这样的事情:
function ParentController($scope, testService) {
testService.getList()
.then(function(data) {
$scope.list = testService.list;
})
.finally(function() {
$scope.$emit('listFetched');
})
function ChildController($scope, testService) {
$scope.$on('listFetched', function(event, data) {
// use the data accordingly
})
}
and my service looks like this
我的服务是这样的
app.service('testService', ['$http', function($http) {
this.list = [];
this.getList = function() {
return $http.get(someUrl)
.then(function(response) {
if (typeof response.data === 'object') {
list = response.data.results;
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
}, function(response) {
// something went wrong
return $q.reject(response.data);
});
}
}])
#7
3
This is my function:
这是我的功能:
$rootScope.$emit('setTitle', newVal.full_name);
$rootScope.$on('setTitle', function(event, title) {
if (scope.item)
scope.item.name = title;
else
scope.item = {name: title};
});
#8
3
<!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('MyApp',[]);
app.controller('parentCtrl',function($scope){
$scope.$on('MyEvent',function(event,data){
$scope.myData = data;
});
});
app.controller('childCtrl',function($scope){
$scope.fireEvent = function(){
$scope.$emit('MyEvent','Any Data');
}
});
</script>
</head>
<body ng-app="MyApp">
<div ng-controller="parentCtrl" ng-model="myName">
{{myData}}
<div ng-controller="childCtrl">
<button ng-click="fireEvent()">Fire Event</button>
</div>
</div>
</body>
</html>
#9
2
I ended up adding an external EventEmitter library to project as a service and injecting it wherever I need. So I can "emit" and "on" anything anywhere without caring for scope inheritance. It is less trouble this way and certainly better performance. Also more readable to me.
最后,我将一个外部的EventEmitter库作为一个服务添加到项目中,并将其注入到我需要的任何地方。因此,我可以“释放”和“在”任何地方,而不关心范围继承。这样做麻烦少了,性能当然也更好了。对我来说也更容易读懂。
Wildcard support: EventEmitter2
通配符支持:EventEmitter2
Good performance: eventemitter3
良好的性能:eventemitter3
Other alternative: Drip
其他:滴
#10
2
Below code shows the two sub-controllers from where the events are dispatched upwards to parent controller (rootScope)
下面的代码显示了事件向上发送到父控制器(rootScope)的两个子控制器
<body ng-app="App">
<div ng-controller="parentCtrl">
<p>City : {{city}} </p>
<p> Address : {{address}} </p>
<div ng-controller="subCtrlOne">
<input type="text" ng-model="city" />
<button ng-click="getCity(city)">City !!!</button>
</div>
<div ng-controller="subCtrlTwo">
<input type="text" ng-model="address" />
<button ng-click="getAddrress(address)">Address !!!</button>
</div>
</div>
</body>
var App = angular.module('App', []);
// parent controller
App.controller('parentCtrl', parentCtrl);
parentCtrl.$inject = ["$scope"];
function parentCtrl($scope) {
$scope.$on('cityBoom', function(events, data) {
$scope.city = data;
});
$scope.$on('addrBoom', function(events, data) {
$scope.address = data;
});
}
// sub controller one
App.controller('subCtrlOne', subCtrlOne);
subCtrlOne.$inject = ['$scope'];
function subCtrlOne($scope) {
$scope.getCity = function(city) {
$scope.$emit('cityBoom', city);
}
}
// sub controller two
App.controller('subCtrlTwo', subCtrlTwo);
subCtrlTwo.$inject = ["$scope"];
function subCtrlTwo($scope) {
$scope.getAddrress = function(addr) {
$scope.$emit('addrBoom', addr);
}
}
http://jsfiddle.net/shushanthp/zp6v0rut/
http://jsfiddle.net/shushanthp/zp6v0rut/
#11
1
Scope(s) can be used to propagate, dispatch event to the scope children or parent.
作用域可以用于将事件传播、分派给作用域子或父对象。
$emit - propagates the event to parent. $broadcast - propagates the event to children. $on - method to listen the events, propagated by $emit and $broadcast.
$emit -传播该事件到父节点。$broadcast -将事件传播给孩子。$on -方法监听事件,由$emit和$broadcast传播。
example index.html:
index . html示例:
<div ng-app="appExample" ng-controller="EventCtrl">
Root(Parent) scope count: {{count}}
<div>
<button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
<button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button><br>
Childrent scope count: {{count}}
</div>
</div>
example app.js:
示例app.js:
angular.module('appExample', [])
.controller('EventCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.$on('MyEvent', function() {
$scope.count++;
});
}]);
Here u can test code: http://jsfiddle.net/zp6v0rut/41/
这里可以测试代码:http://jsfiddle.net/zp6v0rut/41/。
#12
0
According to the angularjs event docs the receiving end should be containing arguments with a structure like
根据angularjs事件文档,接收端应该包含具有类似结构的参数
@params
@params
-- {Object} event being the event object containing info on the event
- {Object}事件是包含事件信息的事件对象
-- {Object} args that are passed by the callee (Note that this can only be one so better to send in a dictionary object always)
——被被callee传递的{Object} args(注意,这只能是一种更好的方式,始终发送一个dictionary对象)
$scope.$on('fooEvent', function (event, args) { console.log(args) });
From your code
美元的范围。$on('fooEvent', function (event, args) {console.log(args)});从你的代码
Also if you are trying to get a shared piece of information to be available accross different controllers there is an another way to achieve that and that is angular services.Since the services are singletons information can be stored and fetched across controllers.Simply create getter and setter functions in that service, expose these functions, make global variables in the service and use them to store the info
另外,如果你想要获取共享的信息,并通过不同的控制器获得,还有另一种方法,那就是角化服务。由于服务是单例信息,所以可以跨控制器存储和获取信息。只需在该服务中创建getter和setter函数,公开这些函数,在服务中创建全局变量并使用它们存储信息
#13
0
The Easiest way :
最简单的方法:
HTML
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="sendData();"> Send Data </button>
</div>
JavaScript
JavaScript
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $rootScope) {
function sendData($scope) {
var arrayData = ['sam','rumona','cubby'];
$rootScope.$emit('someEvent', arrayData);
}
});
app.controller('yourCtrl', function($scope, $rootScope) {
$rootScope.$on('someEvent', function(event, data) {
console.log(data);
});
});
</script>