Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS push to array retrieved by $resource query and save

Checkout the code below. The question is in the comments.

angular.module('MainStreetMower.services', ['ngResource'])
.factory('Videos', function($resource) {
    return $resource('/api/jobs/1/');
});
function VideoListCtrl($scope, Videos) {
    $scope.videos = Videos.query();
    $scope.what = function() {
        // proper way to push to the videos array and $save() the new array.
    }
}
like image 450
drew schmaltz Avatar asked Jan 03 '13 22:01

drew schmaltz


1 Answers

I would say the following:

function VideoListCtrl($scope, Videos) {
    $scope.videos = Videos.query();

    $scope.what = function() {

        var newVideoData = {}; // prepare new video data here from the model
        new Videos(newVideoData).$save(function(video){
          $scope.videos.push(video);
        }); 

    }
}

if you don't want to refresh the whole list. Alternatively you could re-query the collection in the save callback is you expect changes from other sources:

new Videos(newVideoData).$save(function(video){
   $scope.videos = Videos.query();
});

Please note that you could use the save method on the class level. For example, the code above could re-written as:

Videos.save(newVideoData, function(video){
   $scope.videos = Videos.query();
});
like image 107
pkozlowski.opensource Avatar answered Oct 12 '22 18:10

pkozlowski.opensource