AngularJS推送到$resource查询得到的数组并保存

AngularJS push to array retrieved by $resource query and save

本文关键字:数组 保存 resource AngularJS 查询      更新时间:2023-09-26

检查下面的代码。问题在评论中。

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

我想说:

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);
        }); 
    }
}

,如果您不想刷新整个列表。或者,如果您希望从其他来源更改,您可以在保存回调中重新查询集合:

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

请注意,您可以在类级别使用save方法。例如,上面的代码可以重写为:

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