AngularJS - 附加到一个模型以$资源 [英] AngularJS - Append to a model with a $resource

查看:78
本文介绍了AngularJS - 附加到一个模型以$资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的服务:

factory('Post', function($resource) {
    return $resource('/api/post.json', {},
        {
            query: {method:'GET', isArray: false}
        }
    );
})

和我有这样的控制器:

function PostsCtrl($scope, Post) {
    // init
    $scope.page = 0;
    $scope.page_has_next = true;

    $scope.loadMore = function() {
        if($scope.page_has_next) {
            $scope.posts = Post.query({page: ++$scope.page},
                function(data) {
                    $scope.page_has_next = data.has_next;
                }
            );
        }
    }

    $scope.loadMore();
}

这工作得很好,每次 loadMore()直到有没有更多的页面执行模型获取与下一个页面更新。不过,我想追加新的职位,以目前的模式,而不是取代它的,我该怎么办呢?

This works just fine, each time loadMore() is executed the model gets updated with the next page until there are no more pages. However, I want to append the new set of posts to the current model instead of replacing it, how can I do that?

推荐答案

假设帖子是一个数组:

$scope.posts = $scope.posts.concat(Post.query({page: ++$scope.page})

这如果新的岗位与旧的帖子没有重复只会工作。如果有重复的,你必须遍历数组,推动唯一的新职位。

This will only work if the new posts has no duplicates with the old posts. If there are duplicates, you have to traverse the array and push only new posts.

这篇关于AngularJS - 附加到一个模型以$资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆