I've created a controller in Angular that looks like this (edited for brevity):
function AppCtrl($scope, $http, $location, $dataService) {
$scope.projects = $dataService.data.projects;
}
Which correctly loads the $scope.projects
promise from my $dataService
service.
app.service('$dataService', function($q, $http, $location, $rootScope) {
var dataService = this; //Provides access 'this' inside functions below
var projectsDeferred = $q.defer();
$http.get('/api').success(function(data, status, headers, config) {
projectsDeferred.resolve(data.projects);
}).error(function(err) {
projectsDeferred.reject(err);
});
this.data = {projects: projectsDeferred.promise};
//UPDATE FUNCTION
function updateObjectInArray(array, object, newData) {
for(i in array) {
if(array[i] == object) {
if(newData != undefined) {
array[i] = newData;
} else {
return array[i];
}
}
}
return undefined;
}
this.updateProject = function(project, updateData) {
$http.put('/api/projects/' + project._id, updateData)
.success(function(data, status, headers, config) {
updateObjectInArray(dataService.data.projects.$$v, project, data);
}).error(function(data, status, headers, config) {});
};
});
I've created another controller that looks like this, that selects a single project from the array of projects based on the current URL:
function ProjectCtrl($scope, $route) {
//Getting the current project from the array of projects
$scope.project = $scope.projects.then(function(projects) {
for(i in projects) {
if(projects[i]._id == $route.current.params.projectId) {
return projects[i];
}
}
});
}
When I try to run my updateObjectInArray()
function (on the success of my $http.put()
request), my $scope.projects
in AppCtrl
is correctly updated (the array of projects) but my $scope.project
in ProjectCtrl
is not updated. I can log array[i]
inside the updateObjectInArray()
function and it will log exactly what I expect, and I can log $scope.projects
in AppCtrl
and it will update accordingly, but when I try to log $scope.project
in my ProjectCtrl
controller, it isn't updated accordingly.
I thought the reason was because I had to call $rootScope.$apply()
or $rootScope.$digest()
after I updated the array[i]
object in updateObjectInArray()
, however, I get the error that $digest is already in progress
.
What do I need to do to make sure my $scope.project
item in the array gets updated in my ProjectCtrl
? Do I need to resolve a new promise for it?