Angular 1:通过控制器

时间:2017-10-04 05:27:49

标签: javascript angularjs angular-services angular-factory

我以前做过这个,但这次不知道出了什么问题。

服务:

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

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
}

希望我的问题很清楚,为什么局部变量在服务中得到更新,如果它的行为如此......在服务/工厂中获取设置函数的正确方法是什么......对原型函数而言更好在vm中添加功能。

1 个答案:

答案 0 :(得分:0)

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