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

dre*_*ltz 5 javascript angularjs

查看下面的代码.问题出在评论中.

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.
    }
}
Run Code Online (Sandbox Code Playgroud)

pko*_*rce 8

我会说以下内容:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

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

new Videos(newVideoData).$save(function(video){
   $scope.videos = Videos.query();
});
Run Code Online (Sandbox Code Playgroud)

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

Videos.save(newVideoData, function(video){
   $scope.videos = Videos.query();
});
Run Code Online (Sandbox Code Playgroud)