0

I'm trying to pass some data and action within two controllers by using AngularJS $broadcast event. But I'd problems with passing the data as a value (not reference).

What I've done so far is first I created a function that broadcast sendCartPreview event with an object of shoppingCart inside shopping-cart.controller.js

//function inside shopping-cart.controller.js
function sendCartPreview() {
  var shoppingCart = $scope.shoppingCart;
  $rootScope.$broadcast('sendCartPreview', shoppingCart);
}

Then I add a listener of the event on another controller which retrieve the shoppingCart data and pass the data value to sendCartPreview function inside the controller

//function inside chat.controller.js
$scope.$on("sendCartPreview", function(event, message){
  sendCartPreview(message);
})

Basically the sendCartPreview function received the object data and added it to an array of message.

function sendCartPreview(shopping_cart) {
  //some logic here and push the data to an array
  vm.arrayOfMessage.push(shopping_cart);
}

The problem that I'm facing is whenever $scope.shoppingCart value changes, the value inside vm.arrayOfMessage also change according to the respective changes. What I want to achieve in the mean time is passing the data as a value (not by reference) so that everytime $scope.shoppingCart value changed, it will not affect the data inside vm.arrayOfMessage. How do I achieve that? Kindly need your help in this, any kind of help would be appreciated, thanks!

Danny Pranoto
  • 214
  • 2
  • 12

3 Answers3

1

Make a deep copy call like sendCartPreview(angular.copy(message));

Kroderia
  • 623
  • 4
  • 15
1

Thats pretty easy. I assume you have jquery also.

var cart = jQuery.extend(true, {}, shoppingCart);

& broadcast cart.

Abdul Rehman Sayed
  • 6,532
  • 7
  • 45
  • 74
1

You can use angular.copy, for more info: https://docs.angularjs.org/api/ng/function/angular.copy

Leibniz
  • 184
  • 1
  • 5