I'm really having some trouble figuring out how to update the view in AngularJS - just started learning it a few weeks ago, so please go easy. Here's what I'm trying to do: I have a grid of photos that are all being loaded as resources of a factory.
services.js
appName.factory('Photo', ['$resource',
function($resource){
return $resource('http://localhost:3000/json', {}, {
query: { method:'GET', isArray:true }
});
}
]);
Easy enough. So now I want to enable uploading new photos. I'm using the $http
object to create an AJAX call and then on success trying to update the grid.
controllers.js
appName.controller('photogrid', ['$scope', 'Photo',
function($scope, Photo) {
$scope.photos = Photo.query();
console.log($scope.photos);
}
])
appName.controller('uploadFile', ['$scope', '$http', 'Photo',
function($scope, $http, Photo) {
$scope.uploadFile = function(form) {
var data = new FormData();
data.append('title', form.title.value);
data.append('description', form.description.value);
data.append('location', form.location.value);
data.append('uploadfile', form.fileupload.files[0]);
$http({
method: 'POST',
url: '/new',
data: data,
headers: {'Content-Type': undefined},
transformRequest: angular.identity
})
.success(function(data, status, headers, config) {
form.reset();
$('#collapseOne').collapse('hide');
console.log($scope.photos);
$scope.photos = Photo.query();
$scope.$apply();
});
};
}
])
view.html
<ul id="photoGrid">
<li ng-repeat="photo in photos">
<img ng-src="{{ photo.src }}">
</li>
</ul>
I tried building out a new instance of the Photo
model and using the push()
method ($scope.photos.push(newPhoto)
), but that didn't work. If I do that, I can seem to get another resource added to Photo, but then it still doesn't update on the view. I'm not sure what I'm missing - it's probably something simple.