以$范围工作。$排放和。在$ [英] Working with $scope.$emit and .$on

查看:145
本文介绍了以$范围工作。$排放和。在$的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能把我的 $范围对象从一个控制器到另一个使用 $发出。在$ 的方法呢?

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); });
}

它不工作,我认为它应该的方式。怎么办 $发出 $关于工作?

推荐答案

首先,亲子关系的范围很重要。你有两种可能发出一些事件:

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,
  • $emit -- dispatches the event upwards through the scope hierarchy.

我不知道你的控制器(范围)的关系什么,但有几个选项:

I don't know anything about your controllers (scopes) relation, but there are several options:


  1. 如果 firstCtrl 的范围为 secondCtrl 范围的父母,你的code必须
    通过更换工作 $发出 $广播 firstCtrl

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

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]);
    }
    


  • 最后,当你需要派遣从子控制器事件
    到作用域向上可以使用 $范围。$发出。如果 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]);
    }
    


  • 这篇关于以$范围工作。$排放和。在$的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆