我有一个多维数组,我保留了过滤器名称及其列表。
如下面的示例
{"rel":["aa","cc","bb"],"cst":["ff","ee","gg"],"mtm":["hh","jj","ii"]}
" rel"," cst"和" mtm"用作过滤器名称,每个过滤器都有自己的列表显示。
现在我的问题是当我在角度js中使用ng-repeat时,它按照我不想要的字母顺序对滤波器进行排序。
所以我找到了解决这个问题的解决方法。
我的解决方案:
将整数添加到过滤器(键),如下例
{"1rel":["aa","cc","bb"],"2cst":["ff","ee","gg"],"3mtm":["hh","jj","ii"]}
打印键时只需使用一个功能删除第一个字符然后打印。
<script>
angular.module('ngrepeat-sort-remove', []).controller('ngrepeat-sort', function($scope) {
$scope.ngtestrepeat = {"1rel":["aa","cc","bb"],"2cst":["ff","ee","gg"],"3mm":["hh","jj","ii"]};
$scope.removenum =function(key){
return key? key.substr(1) : '';
};
});
</script>
<body ng-app="ngrepeat-sort-remove" ng-controller="ngrepeat-sort">
<div class="ngtest" ng-repeat="(key, value) in ngtestrepeat ">
{{removenum(key)+'-Loop start'}}
<ul>
<li ng-repeat="row in value">{{row}} </li>
</ul>
</div>
</body>
如果您想创建这种更通用的方式,可以使用下划线添加数字,并在显示时使用函数删除它们。
我的角度版本:v1.3.14
如果有人在这里发布更好的解决方案。
答案 0 :(得分:0)
<script>
angular.module('ngrepeat-sort-remove', []).controller('ngrepeat-sort', function($scope) {
$scope.ngtestrepeat = {"rel":["aa","cc","bb"],"cst":["ff","ee","gg"],"mm":["hh","jj","ii"]};
$scope.keyArray=Object.keys($scope.ngtestrepeat);
});
</script>
<body ng-app="ngrepeat-sort-remove" ng-controller="ngrepeat-sort">
<div class="ngtest" ng-repeat="key in keyArray">
{{key+'-Loop start'}}
<ul>
<li ng-repeat="row in ngtestrepeat[key]">{{row}} </li>
</ul>
</div>
</body>
答案 1 :(得分:0)
AngularJS版本up to and including 1.3 sort the keys alphabetically。
因此,作为一个选项,您可以尝试update to AngularJS 1.4+。如果这对您来说是不可接受的,那么建议的解决方法是将您的对象转换为一个数组,该数组在提供给ngRepeat
之前按照您喜欢的顺序排序。使用像toArrayFilter
这样的过滤器可以帮助您解决此问题。
示例:
angular.module('plunker', [])
.controller('MainCtrl', function($scope, $filter) {
var ngtestrepeat = {"rel":["aa","cc","bb"],"cst":["ff","ee","gg"],"mm":["hh","jj","ii"]};
$scope.ngtestrepeat = convertObjToArray(ngtestrepeat);
function convertObjToArray (obj) {
if (!angular.isObject(obj)) return obj;
return Object.keys(obj).map(function (key) {
var value = obj[key];
return angular.isObject(value) ?
Object.defineProperty(value, '$key', { enumerable: false, value: key}) :
{ $key: key, $value: value };
});
}
});
<script src="https://code.angularjs.org/1.3.12/angular.js" ></script>
<html ng-app="plunker">
<body ng-controller="MainCtrl">
<div class="ngtest" ng-repeat="item in ngtestrepeat">
{{item.$key}}<ul><li ng-repeat="row in item">{{row}}</li></ul>
</div>
</body>
</html>
更新:在{{removenum(key)+'-Loop start'}}
之类的绑定中使用函数会使函数removenum
在每个$digest
周期调用,并且可以在长时间内使其变慢数组/重计算,因此如果您关心性能,则不建议这样做。
答案 2 :(得分:0)
您能否使用angular v 1.3.14查看此plunkr解决方案。
在模板中:
<div class="ngtest" ng-repeat="key in objectKeys(ngtestrepeat)" ng-init="value = values[key]">
{{key}}<ul><li ng-repeat="row in objectValues(ngtestrepeat[key])">{{row}}</li></ul>
</div>
在控制器中:
$scope.ngtestrepeat = {"rel":["aa","cc","bb"],"cst":["ff","ee","gg"],"mm":["hh","jj","ii"]};
$scope.objectKeys = function(obj){
return Object.keys(obj);
}
$scope.objectValues = function(obj){
return Object.values(obj);
}