我有<span class="sort-max" ng-click="orderProperty = '-price'">
和一些ng控制器与项目。当我点击按钮时,我需要排序,我做错了什么?
<div class="items-grid" ng-controller="StoreController as store">
<div class="item" ng-repeat="product in store.products | orderBy : 'orderProperty'">
<div class="item-info">
<p class="item-title">{{ product.name }}</p>
<p class="price">{{product.price }}$</p>
</div>
答案 0 :(得分:0)
删除
中的单引号ng-repeat="product in store.products | orderBy : 'orderProperty'"
所以它变成了
ng-repeat="product in store.products | orderBy : orderProperty"
查看此演示: https://plnkr.co/edit/Fa34oC7op5M1fWpXkAgg?p=preview
以下是完整代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="orderByExample1">
<div class="items-grid" ng-controller="StoreController as store">
<a href="#" class="sort-max" ng-click="orderProperty = '-price'">Sort</a>
<div class="item" ng-repeat="product in store.products | orderBy : orderProperty">
<div class="item-info">
<p class="item-title">{{ product.name }}</p>
<p class="price">{{product.price }}$</p>
</div>
</div>
</div>
</body>
</html>
这是JavaScript代码:
(function(angular) {
'use strict';
angular.module('orderByExample1', [])
.controller('StoreController', ['$scope', function($scope) {
$scope.orderProperty = 'price';
$scope.store = {};
$scope.store.products = [
{name: 'Product A', price: 10},
{name: 'Product B', price: 12},
{name: 'Product C', price: 99},
{name: 'Product D', price: 23},
];
}]);
})(window.angular);
答案 1 :(得分:0)
使用ng-repeat="... | orderBy : 'orderProperty'"
,orderProperty
是字符串。您正在通过名为orderProperty
的属性进行排序。
它不会寻找变量名称orderProperty
,因为你把它放在引号之间。
由于您的按钮设置了$scope.orderProperty
,只需删除引号即可:
ng-repeat="product in store.products | orderBy : orderProperty"