我想在六点之后设置七,如何在不更改$ scope.myJson的情况下将其修复为视图。
<div ng-app='app' ng-controller='mainCtrl'>
{{ctrlTest}}<hr/>Ng-Repeat<hr/>
<div ng-repeat="json in myJson">
<li>{{json}}</li>
</div>
</div>
angular.module('app',['QuickList']).controller('mainCtrl', function($scope){
$scope.ctrlTest = "Applying";
$scope.myJson = ["one", "two", "three", "four", "five", "six", "eight", "nine", "seven"]
$scope.jsons = function(){
console.log('callback called');
}
})
答案 0 :(得分:1)
如果您不想更改原始数组,可以提供自定义orderBy函数
<div ng-repeat="json in myJson | orderBy: customSortOrder">
<li>{{json}}</li>
</div>
根据您的使用情况,自定义排序顺序functino可能看起来像这样
const stringToNumber = {
one: 1,
two: 2,
three: 3,
four: 4,
five: 5,
six: 6,
seven: 7,
eight: 8,
nine: 9
}
$scope.customSortOrder = function(item) {
return stringToNumber[item];
}
我更新了您的jsfiddle以获取完整示例http://jsfiddle.net/HgDA7/759/
答案 1 :(得分:0)
以下是我通过创建自定义过滤器和自定义compareFunction
angular.module('app', []).controller('mainCtrl', function($scope) {
$scope.ctrlTest = "Applying";
$scope.myJson = ["one", "two", "three", "four", "five", "six", "eight", "nine", "seven"]
$scope.jsons = function() {
console.log('callback called');
}
}).filter('customsort', function() {
return function(list) {
var sortOrder = {
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9
}
list.sort(function(a, b) {
return sortOrder[a] - sortOrder[b];
})
return list;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='mainCtrl'>
{{ctrlTest}}
<hr/>Ng-Repeat
<hr/>
<div ng-repeat="json in myJson | customsort">
<li>{{json}}</li>
</div>
</div>
答案 2 :(得分:0)
你可以做到这一点的一种方法是在ng-repeat
上使用过滤器或orderBy这是一个例子
angular.module('app',['QuickList']).controller('mainCtrl', function($scope){
$scope.ctrlTest = "Applying";
$scope.myJson = ["one", "two", "three", "four", "five", "six", "eight", "nine", "seven"]
$scope.jsons = function(){
console.log('callback called');
}
$scope.sortFunction = function(obj){
var correctOrder = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
return correctOrder.indexOf(obj);
}
})
这是视图
<div ng-app='app' ng-controller='mainCtrl'>
{{ctrlTest}}<hr/>Ng-Repeat<hr/>
<div ng-repeat="json in myJson | orderBy:sortFunction">
<li>{{json}}</li>
</div>
</div>