Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

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?

like image 859
ps0604 Avatar asked Jan 23 '15 22:01

ps0604


1 Answers

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.

like image 114
Artyom Pranovich Avatar answered Oct 16 '22 18:10

Artyom Pranovich