I am working on an app that interacts with a Mongo database through CRUD operations. Currently, I have a form input where users can add elements, and I want these elements to appear below the form in real-time as they are added. However, at the moment, the new elements only show up after refreshing the page. Interestingly, when I click on an "x" button which triggers an ng-click
event to delete an item (and consequently remove it from the database), the element disappears immediately without requiring a page refresh. Both my POST and DELETE requests are handled using promises, but for some reason, only the delete requests automatically update the DOM, while the post requests do not.
Below is the code snippet of my controller:
app.controller('ListController', function($scope, PlaceService) {
$scope.places = [];
getPlaces();
function getPlaces() {
PlaceService.findAll().then(function(promise) {
//Although $scope.places updates correctly, the changes are not reflected in the DOM
$scope.places = promise.data;
});
};
$scope.submit = function(place) {
if (!place) return alert('No content submitted');
PlaceService.submit(place).then(function(data) {
getPlaces();
}, function(error) {
console.log(error)
});
};
$scope.remove = function(id) {
PlaceService.remove(id).then(function(data) {
getPlaces();
}, function(error) {
console.log(error)
});
}
});
The PlaceService
factory handles communication with the API and looks like this:
app.factory('PlaceService', function($http, $q) {
return {
findAll: function() {
var deferred = $q.defer();
$http.get('/places').then(function(response) {
console.log('Get Request Successful');
return deferred.resolve(response);
}, function(err) {
return console.log(err);
});
return deferred.promise;
},
remove: function(id) {
var deferred = $q.defer();
$http.delete('/places/' + id).then(function(response) {
console.log('Delete Successful');
return deferred.resolve(response);
}, function(err) {
return console.log(err);
});
return deferred.promise;
},
submit: function(entry) {
var deferred = $q.defer();
var jObj = JSON.stringify(entry);
$http.post('/places', jObj).then(function(response) {
console.log('Post Successful');
return deferred.resolve(response);
}, function(err) {
return console.log(err);
});
return deferred.promise;
}
}
});
I have attempted using $timeout
to make $scope.places
reflect the updates in the DOM, but so far, it has not worked as expected.
TLDR: Updates made to $scope.places
in the controller are not being reflected in the DOM