我正在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