如何$scope使用.$emit和.$on方法将对象从一个控制器发送到另一个控制器?
function firstCtrl($scope) {
$scope.$emit('someEvent', [1,2,3]);
}
function secondCtrl($scope) {
$scope.$on('someEvent', function(mass) { console.log(mass); });
}
Run Code Online (Sandbox Code Playgroud)
它不像我认为的那样工作.怎么做$emit和$on工作?
我是Angular.js的新手,我需要在我的应用程序之间进行指令之间的一些通信,我阅读了一些关于链接和需求的文档,但是无法准确理解它是如何工作的.
我有一个简单的例子:活小提琴:http://jsfiddle.net/yw235n98/5/
HTML:
<body ng-app="myApp">
First Directive :
<first-dir >
<h3>{{firstCtrl.data}}</h3>
<button ng-click="firstCtrl.set('NEW VALUE')">Change Value</button>
</first-dir>
Second Directive :
<second-dir>
<h3>{{secondCtrl.data}}</h3>
</second-dir>
Run Code Online (Sandbox Code Playgroud)
Javascript:
(function(){
var app = angular.module('myApp', []);
app.directive("firstDir", function(){
return {
restrict : 'E',
controller : function(){
this.data = 'init value';
this.set = function(value){
this.data = value;
// communication with second Directive ???
}
},
controllerAs : 'firstCtrl'
};
});
app.directive("secondDir", function(){
return {
restrict : 'E',
controller : function(){
this.data …Run Code Online (Sandbox Code Playgroud)