ps0604 ps0604 - 4 months ago 10
AngularJS Question

Angular: $broadcast and $emit send message objects by value or reference?

Given the following code:

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

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


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

Answer

The event consumer receives a pointer to event data.

For example:

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

See this JSFiddle for a demonstration on that.

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

Comments