0

Here is my plunker:

From what I understand, since the Service Variable being shared is an object, the object that gets loaded to the service by controller 1 should be plainly seen by controller2 without the need for $watches or listeners or anything. Am I wrong? How can I get this to work?

JHixson
  • 1,512
  • 2
  • 14
  • 29

1 Answers1

3

I have fixed your plunk: http://plnkr.co/edit/JNBmsjzdj6SHOSK4kPNh.

Your service has an object which you put into a model on your $scope ($scope.item). So far so good. However, you then update your service object with a new object reference ($scope.thisObject) so that $scope.item and myService.myObject are now referencing to completely different objects.

You should only update object properties. See the plunk for details.

So instead of writing:

app.factory('myService',function(){
  var service = {
      myObject:{},
      changeProperty: function(newProperty){
        this.myObject = newProperty;
      }
  };
  return service;
});

You should use:

app.factory('myService',function(){
  var service = {
      myObject:{},
      changeProperty: function(newProperty){
        this.myObject.text = newProperty.text;
      }
  };
  return service;
});

Hope that helps.

jupiter
  • 4,056
  • 1
  • 15
  • 5
  • Gah! I feel so silly. I remember this now from [the Best Practices Video](http://www.youtube.com/watch?v=ZhfUv0spHCY) done a while back. He spent a while covering this exact bug, now that I think of it. His final words on the subject were "If it doesn't have a period, you are doing it wrong" – JHixson May 21 '13 at 20:35