当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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.

}

}

网友答案:

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();
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: