Emidomh Emidomh - 1 year ago 70
AngularJS Question

Trouble with Controllers to manipulate an Object inside a Service

I have an object which should be accessible in many controllers.

This object is inside a Service, has default values and the controller might change those values later.

My problem is that my object inside the service keep values changed by controllers.

When a controller get the object, I want always that it takes the object with default values. (not with values previously modified by an other controller before...)

I have this inside my service :

this.myObject = {'item1' : 'something', 'item2' : 'other' , .....};

I know that it's not correct because of

So I tried to make a method like this :

this.createMyObject = function() {
var obj = myObject;
return obj;

And call
in my controllers but this doesn't work too.

I know that the solution might be obvious.


Answer Source

If what you want is a copy of "myObject", what you want to do is :

var obj = angular.copy(myObject);

Because var obj = myObject; will just copy the reference of the object, not its content.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download