After storing data received from a service in my controller and making edits, I noticed that the changes also reflect back in the original data stored in the service.
/* Omitted backend connection section and markdown editor JS code for brevity */
var myApp = angular.module('myApp', []);
// The PostService in my app caches blog post data from the server on the client side and retrieves single posts
myApp.factory('PostService', function ($log, $filter, $http) {
var data;
// Sample data pulled from server
data = [{
id: 99999,
text: "Hello"
}];
// Function to retrieve a specific post from the cached data array
var getData = function (id) {
if (id !== undefined) {
var arr = $filter('filter')(data, {
id: id
});
if (arr.length === 0) {
$log.error('PostService:: getData(' + id + '):: Post Not Found');
return 'not_found';
} else {
$log.debug('PostService:: getData(' + id + '):: Post returned');
return arr[0];
}
} else {
return data;
}
};
return {
getData: getData
};
});
function ctrl($log, $scope, PostService) {
var edit = this;
// Set example post id for editing
edit.editingId = 99999;
// Copy the blog post data to be edited
edit.data = PostService.getData(edit.editingId);
}
This setup is intended for a markdown editor. The goal was to fetch the data from the service into the controller, allow editing, and then update the service with the modified version upon clicking a "Save" button. If this behavior aligns with Angular's databinding principle, what would be a more effective approach to achieve the desired outcome?
Update
In response to feedback from PSL's comment and Thibaud Sowa's answer, I have modified the getData()
function to return a copy using angular.copy()
. However, it appears challenging to copy a single object from an array (e.g., angular.copy(arr[0])
), as it still returns the entire array. Refer to the updated JSFiddle.
Update 2
Upon further investigation, I realized my error and made the necessary corrections, as depicted in the updated fiddle. Thank you for your valuable insights.