angularjs实现点击加载更多
做个人博客时遇到这个需求,首先说下遇到难点: 对于第一点:
具体如下:directive.js indexAPP.directive('pagination',function($compile) {
return {
restrict: 'AEMC',// E = Element,A = Attribute,C = Class,M = Comment
scope: true,template: "<input type='button' value='加载更多'/>",link: function($scope,iElm,iAttrs,controller) {
var i =1; //计数,第几次加载
$("pagination input").bind("click",function() {
$("pagination input").attr("disabled","true");
$("pagination input").val("正在加载....败着急");
$scope.getAbstract();
var el = $compile("<articleblock ng-repeat='article in articles" + i + "'></articleblock>")($scope); //重新compile一下,再append
i++;
$("#main").append(el);
})
}
}
});
对于第二点:查阅资料发现可以用promise模拟同步,但我选择了投机取巧的解决方案,就是,在第一次未加载完之前,把按钮设为禁用,需要用到then() articleModule.controller('ArticleCtrl',function($scope,$http) {
var offset = 0,//当前页数
limit = 2,//一页多少篇
i = 0; //第几次加载
$scope.getAbstract = function() {
$http.get('api/getPostAbstract',{
params: {
offset,limit
}
})
.success(function(data,status,headers,config) {
if (i == 0) {
$scope.articles = data;
i++;
} else if (i >= 1)
$scope["articles" + i++] = data;
offset = offset + limit;
}).error(function(data,config) {
throw new Error('Something went wrong...');
}).then(function(result) {
$("pagination input").removeAttr("disabled");
$("pagination input").val("点击加载更多");
if(result.data.length<=0) $("pagination input").val("没有更多文章啦~");
});
}
$scope.getAbstract();
});
article.html <article class="block post" id="{{article.id}}"> <span class="round-date"> <span class="month" ng-bind="(article.post_time |dateUtil|date:'M')+'月'"></span> <span class="day" ng-bind="article.post_time |dateUtil| date:'d'"></span> </span> <header> <p class="title"> <a href="articleDetail.html?{{article.id}}" ng-bind="article.title" target="_blank"></a> </p> <p class="article-meta"> <i class="fa fa-paper-plane-o" ng-bind="article.post_time | date:'yyyy-MM-dd'"></i> <i class="fa fa-eye" ng-bind="article.pageviews"></i> <i class="fa fa-comment-o" ng-bind="article.comments"></i></p> <div class="tag-meta"> <div class="tag" ng-repeat="tag in article.tags" ng-bind="tag"></div> </div> </header> <div class="article-content animate-show" ng-bind-html="article.post_abstract | to_trusted" ng-show="showMe"></div> <span class="fa fa-angle-double-up compress" ng-click="toggle()"></span> </article>
我知道我这里通过两边都设置i,不大好,但也暂时找不到好办法,我想在then里面return当前的i,但是好像实现不了,嗯嗯嗯,纠结,而且http服务貌似应该放在factory方便使用? 我这样功能都能实现,就是感觉代码质量不够高,希望能早到更好的办法 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |