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

瘦欲@ 提交于 2019-11-30 22:33:37

When Angular sees

<h1>Does Not Work: {{badPerson.name}}</h1>

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!