Angular 1: service variable getting updated via controller

54 Views Asked by At

I have done this before, but this time dont know what went wrong.

A service:

angular.module('module')
  .service("BaseService", function() {
    var vm = this;
    var testValue = {a:1,b:2};
    vm.getTestValue = function(){
        return testValue;
    }
  });

A method in a Controller:

vm.getTest = function(){
      console.log(BaseService.testValue) // undefined - cool
      console.log(BaseService.getTestValue()) //{a: 1, b: 2} - cool
      var value = BaseService.getTestValue();
      console.log(value) // {a: 1, b: 2} - cool
      value.a = 20; // updated local object
      console.log(value) // {a: 20, b: 2} -cool
      console.log(BaseService.getTestValue())-- {a: 20, b: 2} -- ??? why
}

Hope my question is clear, why a local variable is getting updated within service and if it behaves like that..what's the proper way of getting setting functions in services/factories....would it be better to prototyping functions rather appending fuctions in vm.

1

There are 1 best solutions below

2
On

Your variable (testValue) in the service is an object which belongs to the reference types. When you use it in the controller it gets only the reference, the object remains the same. You actually have 2 reference to the same object, so changing it's properties via the one of the references affects the object. So you get the changed object.

Imagine a room with two doors. Here doors are your references and the room is the object itself. When you come in through one door and change something in the room, then coming in from the another one you can see the changes in the room.

If you don't want to get the current object, you can copy the object in the function and return the copy.

vm.getTestValue = function() {
    return angular.copy(testValue);
}