我正在AngularJS中開發一個Web應用程序。我對JavaScript中的引用感到困惑。對象的更改何時影響其引用?JavaScript中的對象值和對象數組
例如,我在我的應用程序中有一個控制器。我使用該控制器上傳文件並在工廠保留文件信息。
$scope.fileArray = [];
...
...
uploadFiles(file){
$scope.fileArray.push(file);
..
..
//on success
file.params = data["parameters"]; //an array of strings about file path and name
...
...
}
在uploadFiles函數中,我將文件對象壓入fileArray。然後,當我更改或向文件對象添加新屬性時,我可以在fileArray中看到這些更改。
var fileInfo = {
infoArray : $scope.fileArray
}
fileFactory.keepFileInfo(fileInfo);
然後我把這個數組放在工廠裏。但是這次對$ scope.fileArray的改變並未在工廠中反映出來。這裏的邏輯是什麼?
編輯
我錯了。控制器對象效果工廠也在變化。我寫了這個最小的應用程序來清楚地看到它,在我的應用程序中,我必須在其他地方犯錯。
var testApp = angular.module('testApp', []);
testApp.controller('TestController', function($scope, TestFactory) {
$scope.fileArray = [];
var files = [];
files[0] = {
parameters : {
name : 'file1.txt',
path : "user/files"
}
}
$scope.fileArray.push(files[0]);
files[1] = {
parameters : {
name : 'file2.txt',
path : "user/files"
}
}
$scope.fileArray.push(files[1]);
files[2] = {
parameters : {
name : 'file3.txt',
path : "user/files"
}
}
$scope.fileArray.push(files[2]);
TestFactory.setFileArray($scope.fileArray);
files[0].parameters["name"] = "changed file name";
console.log($scope.fileArray); //here writes "changed file name"
console.log(TestFactory.getFileArray()); //here writes "changed file name", too
});
testApp.factory('TestFactory', function() {
var factory = {};
var fileArray = [];
factory.setFileArray = function(files) {
fileArray = files;
}
factory.getFileArray = function() {
return fileArray;
}
return factory;
});
請顯示所有相關的代碼。看起來你沒有在控制器中共享工廠數組,如果你使用'$ scope'來定義它,因爲在工廠沒有$ scope – charlietfl