简体   繁体   中英

angular js Service/Factory attributes behavior

I have a question about AngularJS behavior (JS behavior in general)

I have an Angular factory injected into a controller.

Here's a snippet of the controller code

$scope.localObjCollection= myObjFactorySvc.getObjCollection();

Let's assume that myObjFactorySvc.getObjCollection() returns the following object

[{"id":1"name":null,"address":null,"email":null},
{"id":2"name":null,"address":null,"email":null},
{"id":3"name":null,"address":null,"email":null},
{"id":4"name":null,"address":null,"email":null},
]

So, I'm pretty much using the factory to get the collection and storing it in $scope.localObjCollection . My question is does $scope.localObjCollection have the value (copy) of the data returned by getObjCollection() or just a reference.

So if somewhere down in the controller source code, if I do $scope.localObjCollection.push(newObj) , does it also update the original collection in the Factory? It should I guess but I would like to understand the correct behavior

An array in JavaScript is an object and objects in JS are always passed/assigned by reference. Therefore your code would also update the original collection in the Factory, assuming that your myObjFactorySvc.getObjCollection() is something like this:

myObjFactorySvc.getObjCollection = function() { return someArrayVariable; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM