AngularJS: 如何避免将引用从一个范围复制到另一个范围?

AngularJS: How to avoid copying reference from one scope to another?

我有以下代码,我需要在其中创建一个实例,该实例已更新并保存,而没有对以前的范围进行任何更改。

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中正确地做到这一点?

非常感谢任何建议。

在 javascript 中,对象通过引用传递。因此,当您在不同的变量中复制对象时,引用保持不变,因此对任何一个的任何更改都将应用于两个对象。

要创建具有不同引用的副本,您可以使用

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

或者使用 loadash 或下划线,例如

_.extend({},oldObj)