我有以下代码,我需要创建一个已更新并保存的单个实例,而不会对先前的范围进行任何更改。
console.log("Trying to save playlist");
console.log($rootScope.selectedSounds);
$scope.playlistInstance = $rootScope.selectedSounds;
var preparedSoundsForSave = [];
angular.forEach($scope.playlistInstance, function (selectedSound, key){
console.log("Sound to playlist is following:");
console.log(selectedSound);
var selectedSoundInstance = selectedSound;
selectedSoundInstance.state = 0;
delete selectedSoundInstance.mediaInstance ;
preparedSoundsForSave.push(selectedSoundInstance);
});
// Create the new object which has been saved
$scope.playlist.name = $scope.playlistName;
$scope.playlist.tracks = preparedSoundsForSave;
console.log($scope.playlist);
existingPlaylists.push($scope.playlist);
localStorageService.set("playlists", existingPlaylists);
$ionicLoading.show({
duration: 1000,
template: $translate.instant('SAVED')
});
$scope.playlistName = "";
所以我创建了单个实例,更改了一些值并保存了更改的数组。 问题是,更改会自动传递给:
$rootScope.selectedSounds
没有任何理由。
我想问一下,我怎么能正确地在AngularJS中做到这一点?
非常感谢您的任何建议。
答案 0 :(得分:0)
在javascript对象中通过引用传递。因此,当您在另一个变量中复制对象时,引用保持不变,因此对任何一个的任何更改都将应用于该对象。
要创建具有不同引用的副本,您可以使用
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
或者使用loadash或下划线,如
_.extend({},oldObj)