Dirty checking with shared service between controllers, One way works the other does not?

后端 未结 1 356
你的背包
你的背包 2021-01-06 05:34

While attempting to answer a question regarding sharing data between two separate controllers I ran into a question .

I usually use services for for this task and

1条回答
  •  离开以前
    2021-01-06 06:18

    When Angular sees

    Does Not Work: {{badPerson.name}}

    it sets up a $watch on object badPerson. Looking at your controller, $scope.badPerson is a reference to object DataService.badPerson. All is fine so far... the problem happens here:

    setActivePersonDoesNotWork: function (person) {
        People.badPerson = person;
    }
    

    When this function executes, badPerson is assigned a new/different object reference, but the controller is still $watching the old/original object reference.

    The fix is to use angular.copy() to update the existing badPerson object, rather than assigning a new reference:

    setActivePersonDoesNotWork: function (person) {
        angular.copy(person, People.badPerson);
    }
    

    This also explains why setActivePersonWorks() works -- it does not assign a new object reference.

    0 讨论(0)
提交回复
热议问题