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


while attempting answer question regarding sharing data between 2 separate controllers ran question .

i use services for task , began create jsfiddle, not work.

after bit of debugging if created properties dynamically in setactivepersonworks(person) dirty checking worked , second controller showed correct value.

if assigned value in setactivepersondoesnotwork() did not.

if used $timeout() able verify dataservice.badperson did indeed contain correct data.

am doing wrong? guess if $apply() work correctly, why creating values dynamically cause things work?

working example:

var mytest = angular.module("mytest", []); mytest.factory("dataservice", function () {     var people = {         goodperson: {},         badperson: {},         setactivepersonworks: function (person) {             people.goodperson.name = person.name;             people.goodperson.id = person.id;         },         setactivepersondoesnotwork: function (person) {             people.badperson = person;         }     };     return people; });  function viewcontroller($scope, dataservice, $timeout) {     $timeout(function () {         dataservice.setactivepersonworks({             id: 1,             name: "good mark"         });         dataservice.setactivepersondoesnotwork({             id: 2,             name: "bad mark"         });     }, 1000); }  function detailcontroller($scope, dataservice, $timeout) {     $scope.goodperson = dataservice.goodperson;     $scope.badperson = dataservice.badperson;      $timeout(function(){         $scope.message = "dataservice has value: " + dataservice.badperson.name + " $scope.badperson " + $scope.badperson.name;     }, 2000); } 

the <html/>

<div ng-app="mytest">     <div ng-controller="viewcontroller"></div>     <div ng-controller="detailcontroller">          <h1>works: {{goodperson.name}}</h1>           <h1>does not work: {{badperson.name}}</h1>         {{message}}     </div> </div> 

on jsfiddle

when angular sees

<h1>does not work: {{badperson.name}}</h1> 

it sets $watch on object badperson. looking @ controller, $scope.badperson reference object dataservice.badperson. fine far... problem happens here:

setactivepersondoesnotwork: function (person) {     people.badperson = person; } 

when function executes, badperson assigned new/different object reference, controller still $watching old/original object reference.

the fix use angular.copy() update existing badperson object, rather assigning new reference:

setactivepersondoesnotwork: function (person) {     angular.copy(person, people.badperson); } 

this explains why setactivepersonworks() works -- not assign new object reference.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -