我正在尝试在向其推送新元素后对数组进行排序,并在我的ng-repeat上显示更改。它没有按预期工作,看起来我的范围与视图断开连接。
我有一个带有ng-repeater的人员阵列。然后是一个列标题,按姓氏对数组进行排序。最后一个按钮,用于添加新人并按名字自动对数组进行排序,并在视图上显示。
这是我的HTML代码:
谢谢!
<div ng-app="myApp">
<div ng-controller='myController'>
<div>
<input type="button" value="Filter All" ng-click="filterAll()" />
<input type="button" value="Add & Filter" ng-click="AddNFilter()" />
</div><br/>
<div><a href="" ng-click="orderByField='lname'; reverseSort = !reverseSort">Order by LName</a></div>
<div ng-repeat="p in person | orderBy:orderByField:reverseSort">
{{p.name}} {{p.lname}}
</div>
</div>
</div>
我的javascript:
var app = angular.module('myApp', []);
app.controller('myController', function ($scope, $filter) {
var person = [{
name: "Seimour"
, lname: "Duncan"
}
, {
name: "Engy"
, lname: "Wook"
}
, {
name: "Dame"
, lname: "Eyola"
}];
$scope.person = person;
$scope.filterAll = function () {
alert('Before filter: ' + $scope.person[0].name);
var filtered = $filter('orderBy')($scope.person, 'name');
$scope.person = filtered;
alert('After filter: ' + $scope.person[0].name);
}
$scope.AddNFilter = function () {
var p = [{
name: "Ayesha"
, lname: "Shexper"
}];
alert('Length before adding: ' + $scope.person.length);
$scope.person.push(p);
var filtered = $filter('orderBy')($scope.person, 'name');
$scope.person = filtered;
alert('Length after adding: ' + $scope.person.length);
}
});
答案 0 :(得分:0)
首先,您必须将p
变量转换为对象,而不是对象数组,以使代码工作:
var p = {
name: "Ayesha",
lname: "Shexper"
};
其次,您不需要再次对范围内的对象进行排序。如果您更改传递给orderBy过滤器的变量以便按正确的属性进行过滤就足够了:
$scope.orderByField = 'name';
$scope.reverseSort = !$scope.reverseSort; // Optional! Do it if you want to reverse the sorting
您应该在filterAll和AddNFilter函数中执行此操作,以便在每次单击任何图标时更新过滤器的属性。单击Order by LName
我更新了你的小提琴here