我试图动态更改ng-repeat命令。
我有一个2个字符串的列表,它们假定按对象的属性排序,而一个函数则计算对象的总参与度。
控制器
/**
* the available filters for the sort
* @type []
*/
$scope.orders = [
{name: "Newest", order: '-created_at'},
{name: "Oldest", order: 'created_at'},
{name: "Most Engaged", order: 'totalEngagement'}
];
$scope.totalEngagement = function (content) {
total = 0;
if (content.likes_count)
total -= content.likes_count;
if (content.comments_count)
total -= content.comments_count;
return total;
};
/**
* Set the chosen order to sort the buzz content by
* @param order - the chosen order
*/
$scope.setOrder = function (order) {
$scope.selectedOrder = order;
};
视图
<div ng-init="setOrder(orders[0])" class="col-sm-6 col-md-4 col-lg-3 mix "
ng-repeat="content in campaign.content | orderBy:selectedOrder.order">
现在,2 order by属性工作正常,但是当我选择订单时函数不会触发。如果我正在推出而不是selectedOrder.order,那么函数名称,订单工作正常。
我添加了一个plunker示例
答案 0 :(得分:0)
“最多订婚”订单的订单字段应该是函数本身,而不是函数的名称。如果您传递一个字符串,angular将尝试按对象的字段totalEngagement
排序,并且它们没有这样的字段。
因此,简而言之,您需要的是
$scope.totalEngagement = function (content) {
total = 0;
if (content.likes_count)
total -= content.likes_count;
if (content.comments_count)
total -= content.comments_count;
return total;
};
$scope.orders = [
{name: "Newest", order: '-created_at'},
{name: "Oldest", order: 'created_at'},
{name: "Most Engaged", order: $scope.totalEngagement}
];
或者,由于该功能不在范围内,
$scope.orders = [
{name: "Newest", order: '-created_at'},
{name: "Oldest", order: 'created_at'},
{name: "Most Engaged", order: totalEngagement}
];
function totalEngagement(content) {
total = 0;
if (content.likes_count)
total -= content.likes_count;
if (content.comments_count)
total -= content.comments_count;
return total;
}