角度:$ broadcast和$ emit通过值或引用发送消息对象? [英] Angular: $broadcast and $emit send message objects by value or reference?

查看:59
本文介绍了角度:$ broadcast和$ emit通过值或引用发送消息对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

var msg = {
  field1: val1,
  field2: val2,
  // more fields
};

$scope.$broadcast("EventName", msg);

事件使用者是否收到指向msg或副本的指针?

The event consumer receives a pointer to msg or a copy?

推荐答案

事件使用者接收指向事件数据的指针.

例如:

<div ng-controller="MyCtrl">
    <input type="text" ng-model="name.name"/>
    <button ng-click="broadcast()">Broadcast event</button>
</div>
<div ng-controller="MyCtrl2">
    <input type="text" ng-model="name2.name"/>
</div>

function MyCtrl($scope,$rootScope) {
    $scope.name = {name: "MyCtrl"};
    $scope.broadcast = function(){
        $rootScope.$broadcast('someEvent', $scope.name);
    };
}

function MyCtrl2($scope,$rootScope) {
    $scope.name2 = null;
    $scope.$on('someEvent', function(event, data){
        $scope.name2 = data;
    });
}

有关此示例,请参见 JSFiddle .

See this JSFiddle for a demonstration on that.

只需使用按钮广播第一个input字段中的值,然后尝试更改任何input字段的值.

Just broadcast the value from the first input field using the button and then try to change the value of any input field.

这篇关于角度:$ broadcast和$ emit通过值或引用发送消息对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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