使用 $scope.$emit 和 $scope.$on [英] Working with $scope.$emit and $scope.$on

查看:49
本文介绍了使用 $scope.$emit 和 $scope.$on的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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$on 如何工作?

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:

  1. 如果 firstCtrl 的作用域是 secondCtrl 作用域的父级,你的代码应该通过在 firstCtrl 中将 $emit 替换为 $broadcast 来工作:

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

  • 最后,当你需要从子控制器分派事件时向上作用域,您可以使用 $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屋!

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