我正在创建一个Ionic应用程序,从joomla K2网站上提取文章。我正在使用$http,我的url以'?format=json‘结尾,这是非常好的。然而,网站,我是从它的文章每隔几分钟更新数据,所以我需要一个方法,让用户能够刷新页面。我已经实现了Ionics来刷新,它的工作非常好,只不过它不只是插入新的文章,它只是将所有的文章附加到我的数组中。是否有可能只是迭代当前的文章、时间戳或ID(我在localStorage中缓存文章)来引入新的文章?我的工厂是这样的:
.factory('Articles', function ($http) {
var articles = [];
storageKey = "articles";
function _getCache() {
var cache = localStorage.getItem(storageKey );
if (cache)
articles = angular.fromJson(cache);
}
return {
all: function () {
return $http.get("http://jsonp.afeld.me/?url=http://mexamplesite.com/index.php?format=json").then(function (response) {
articles = response.data.items;
console.log(response.data.items);
return articles;
});
},
getNew: function () {
return $http.get("http://jsonp.afeld.me/?url=http://mexamplesite.com/index.php?format=json").then(function (response) {
articles = response.data.items;
return articles;
});
},
get: function (articleId) {
if (!articles.length)
_getCache();
for (var i = 0; i < articles.length; i++) {
if (parseInt(articles[i].id) === parseInt(articleId)) {
return articles[i];
}
}
return null;
}
}
});我的控制器:
.controller('GautengCtrl', function ($scope, $stateParams, $timeout, Articles) {
$scope.articles = [];
Articles.all().then(function(data){
$scope.articles = data;
window.localStorage.setItem("articles", JSON.stringify(data));
},
function(err) {
if(window.localStorage.getItem("articles") !== undefined) {
$scope.articles = JSON.parse(window.localStorage.getItem("articles"));
}
}
);
$scope.doRefresh = function() {
Articles.getNew().then(function(articles){
$scope.articles = articles.concat($scope.articles);
$scope.$broadcast('scroll.refreshComplete');
});
};
})发布于 2015-06-12 08:53:35
使用underscore.js进行简单的过滤功能。
例如:
获取已加载项的所有id(我相信有一些独特的字段,如id)
http://underscorejs.org/#pluck
var loadedIds = _.pluck($scope.articles, 'id');如果item.id已经在loadedIds列表中,则拒绝所有项目。
http://underscorejs.org/#reject
http://underscorejs.org/#contains
var newItems = _.reject(articles, function(item){
return _.contains(loadedIds, item.id);
});加入新的项目和存在:
$scope.articles = newItems.concat($scope.articles);或
http://underscorejs.org/#union
$scope.articles = _.union(newItems, $scope.articles);实际上,_.union()可以管理和删除重复项,但是我会使用item.id进行手动筛选。
https://stackoverflow.com/questions/30798064
复制相似问题