As I work on developing a web application using AngularJS, my focus is on understanding how references in JavaScript operate. Specifically, I am curious about when changes made to an object impact its references.
For instance, within my application's controller, I handle file uploads and manage file data through a factory.
$scope.fileArray = [];
...
...
uploadFiles(file){
$scope.fileArray.push(file);
..
..
//on success
file.params = data["parameters"]; //an array of strings about file path and name
...
...
}
When I push the file object into the fileArray within the uploadFiles function, any subsequent changes or additions to the file object are reflected in the fileArray.
var fileInfo = {
infoArray : $scope.fileArray
}
fileFactory.keepFileInfo(fileInfo);
Subsequently, I store this array in the factory. Surprisingly, changes made to `$scope.fileArray` do not get updated in the factory. What could be causing this discrepancy?
EDIT
I stand corrected. Changes to the controller object also influence the factory. To better grasp this concept, I built a basic application demonstrating this flow. It appears that the issue lies elsewhere in my main application.
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); //this will display "changed file name"
console.log(TestFactory.getFileArray()); //which will also show "changed file name"
});
testApp.factory('TestFactory', function() {
var factory = {};
var fileArray = [];
factory.setFileArray = function(files) {
fileArray = files;
}
factory.getFileArray = function() {
return fileArray;
}
return factory;
});