AngularJS orderby doesn't work when orderby-property is edited
我有一个范围内的对象列表,并希望对其进行迭代,以按某种属性排序的方式显示其某些属性,然后进行更改。
ng-repeat用于显示绑定到列表中每个对象的文本框,以及应用"位置"作为参数的orderby过滤器。
同样,位置也是可编辑的!
现在我们一次更改某个对象的位置(按预期角度对列表进行重新排序),然后更改两次。 Angular不会对列表重新排序。
谁能解释一下如何解决这种仅一次重新订购的情况,以及这种行为的原因是什么?
这是小提琴:JSFiddle
的HTML
1 2 3 4 5 6 7 8 9 | <p> List of activities: </p> <textarea type="text" ng-model="activity.name"> </textarea> {{activity.name}} <input type="text" ng-model="activity.position"> |
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 | var myApp = angular.module('myApp',[]); function MyCtrl($scope) { $scope.model = { activities: [ {name:"activity 1", position: 1}, {name:"activity 2", position: 2}, {name:"activity 3", position: 3}, {name:"activity 4", position: 4}, {name:"activity 5", position: 5} ] }; } |
来了
为什么代码表现得如此?
我该如何解决?
您有两个选择。 第一种选择是将
1 2 3 4 5 6 7 8 9 10 | myApp.directive('integer', function() { return { require: 'ngModel', link: function(scope, el, attr, ctrl){ ctrl.$parsers.unshift(function(viewValue){ return parseInt(viewValue, 10); }); } }; }); |
该代码的作用是将每个值解析为整数以使其工作。
因为您的
您需要创建自定义排序。
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | {{activity.name}} <input type="text" ng-model="activity.position"> $scope.getOrderedData = function(){ return $scope.model.activities.sort(compare); }; var compare = function(a,b){ if (parseInt(a.position) < parseInt(b.position)) return -1; if (parseInt(a.position) > parseInt(b.position)) return 1; return 0; }; |
这将适用于每个AngularJS版本。
有关整个工作示例,请参见此JSFiddle。
希望能帮助到你!