博客列表页优化
博客快写了20篇了,首页有点太长了。考虑优化一下。
显示摘要
之前在列表页也是全文显示,这里做一个简单的截取,仅取文章前200字符做为摘要。为了避免把句子和Mardown语法截取一半,就会造成混乱,做法是找200字符最后最近的换行符作为截取点。代码如下,虽然有点暴力,显示效果还可以:
for (var i = articles.length - 1; i >= 0; i-=1) {
var content = articles[i].content;
if (content.length > 200) {
var idx = content.indexOf('\n', 200);
if (idx === -1 || idx > 400) {
idx = 200;
}
articles[i].content = content.substring(0, idx);
}
}
分页
Angular UI Bootstrap提供了一个Pagination组件,而且本博客的Mean.io框架默认就集成了此库,所以分页的UI用下面的一行就搞定了:
<pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()"></pagination>
现在要做的就是实现翻页功能了。步骤如下: 1. 修改Server端的controller,使其支持分页获取:
exports.all = function(req, res) {
var page = req.param('page') || 1;
var num = req.param('num') || 20;
Article.find().sort('-created').skip((page - 1) * num).limit(num)
.populate('user', 'name username').exec(function(err, articles) {
if (err) {
return res.json(500, {
error: 'Cannot list the articles'
});
}
...
res.json(articles);
});
};
注意这里获取了参数page
和num
。 2. Server端添加路由:
app.route('/articles/total').get(articles.total); //获取文章总数
app.route('/articles/p').get(articles.all); //分页获取
3. 在Client端口Factory中,添加两个API:
angular.module('mean.articles').factory('Articles', ['$resource',
function($resource) {
return $resource('articles/:articleId', {articleId: '@_id'},
{
...
total: {method: 'GET', params: {articleId: 'total'}},
page:{method: 'GET', params: {articleId: 'p'}, isArray: true},
});
}
]);
这里面有一点triky,就是用total
和page
方法中,用相应的API path(这里是total和p)替换参数articleId
,就实现了对路由/articles/total
和/articles/p
的访问。 4. Client端Controller添加方法:
// 获取文章的数量,用于total-items="totalItems"
$scope.updatePaginate = function() {
Articles.total(function(ret){
$scope.totalItems = ret.total;
});
};
// 上面的html标签中,ng-change="pageChanged()",切换页面的时候会调用此函数
$scope.pageChanged = function() {
Articles.page({
page: $scope.currentPage,
num: $scope.itemsPerPage,
}, function(articles) {
$scope.articles = articles;
});
};
至此就实现了全部的分页功能。