Accidentally, I managed to create something that works but feels like it shouldn't! Essentially, I have a JSON data with a list of items that can be selected by the user, modified, and then saved. Here is a simplified version of the code:
app.service("ItemData", ["$http", function ItemDataService($http) {
this.items = [];
var _this = this;
this.fetch = function() {
var promise = $http.get("items.json");
promise.then(
function(payload) {
_this.items = payload.data;
console.log(_this.items);
}
);
return promise;
};
this.getFirstItem = function() {
return this.items[0];
}
this.update = function() {
console.log(this.items)
};
}]);
app.controller("PageCtrl", ["$rootScope", "ItemData", function($rootScope, ItemData) {
var _this = this;
$rootScope.item = null;
var promise = ItemData.fetch();
promise.then(
function(payload) {
setTimeout(function() {
$rootScope.item = ItemData.getFirstItem();
$rootScope.item.name = "why does this change the original service?";
ItemData.update();
}, 5000);
}
);
}]);
When ItemData.update
is called, the logs reveal the changes made. However, my expectation was for $rootScope.item
to be a copy rather than a reference to the original. Isn't that the usual behavior with function returns? Why does it also affect the original data here?
I am new to AngularJS, so there might be better approaches. Hence, my question has two parts - why does the current code behave this way, and are there alternative methods?