Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - 使用$ scope。$ emit和$ scope。$ on(Working with $scope.$emit and $scope.$on)

How can I send my $scope object from one controller to another using .$emit and .$on methods?

(如何使用.$emit.$on方法将$scope对象从一个控制器发送到另一个控制器?)

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?

($emit$on work如何运作?)

  ask by Paul Kononenko translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

(我对控制器(范围)关系一无所知,但有几种选择:)

  1. If scope of firstCtrl is parent of the secondCtrl scope, your code should work by replacing $emit by $broadcast in firstCtrl :

    (如果范围firstCtrl是母公司secondCtrl范围,你的代码应该通过更换工作$emit$broadcastfirstCtrl :)

     function firstCtrl($scope) { $scope.$broadcast('someEvent', [1,2,3]); } function secondCtrl($scope) { $scope.$on('someEvent', function(event, mass) { console.log(mass); }); } 
  2. 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 (ie also secondCtrl ).

    (如果您的范围之间没有父子关系,您可以将$rootScope注入控制器并将事件广播到所有子范围(即secondCtrl )。)

     function firstCtrl($rootScope) { $rootScope.$broadcast('someEvent', [1,2,3]); } 
  3. Finally, when you need to dispatch the event from child controller to scopes upwards you can use $scope.$emit .

    (最后,当您需要将子控制器中的事件调度到范围向上时,您可以使用$scope.$emit 。)

    If scope of firstCtrl is parent of the secondCtrl scope:

    (如果firstCtrl范围是firstCtrl范围的父secondCtrl :)

     function firstCtrl($scope) { $scope.$on('someEvent', function(event, data) { console.log(data); }); } function secondCtrl($scope) { $scope.$emit('someEvent', [1,2,3]); } 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...