我必须根据我在ng-change
上调用函数的用户输入对对象数组进行排序。数组需要根据对象数组中的name
进行排序。
数组
[{"id":1,"name":"android","taggings_count":5,"category":null},{"id":2,"name":"ruby","taggings_count":7,"category":null},{"id":3,"name":"java","taggings_count":3,"category":null}]
功能签名
$scope.searchTags = (tagText) ->
其中tagText
是我从ng-change
那么,如何将用户输入,tagText
映射到数组中的name
属性并进行比较?
答案 0 :(得分:1)
您可以将orderBy与自定义比较器一起使用,如下一个示例中所示。这里的顶部是名称以输入文本开头的对象
angular.module('app', [])
.controller('ctrl', function($scope, $filter) {
$scope.arr = [{
"id": 1,
"name": "android",
"taggings_count": 5,
"category": null
}, {
"id": 2,
"name": "ruby",
"taggings_count": 7,
"category": null
}, {
"id": 3,
"name": "java",
"taggings_count": 3,
"category": null
}, {
"id": 4,
"name": "javascript",
"taggings_count": 3,
"category": null
}];
var orderBy = $filter('orderBy');
$scope.searchedText = function(txt) {
$scope.ordered = orderBy($scope.arr, function(el){
if(el.name.startsWith(txt)){
return el.name.replace(txt,'').length;
}
return 100;
});
}
$scope.searchedText('');
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input ng-model="text" ng-change="searchedText(text)" type="text" />
<div ng-repeat="a in ordered">{{a}}</div>
</div>
&#13;
答案 1 :(得分:0)
您可以使用KnightCoder之前的代码。
/*
* RandomKnight - Gists of code to get random values from numbers and arrays
* * * * Small, fast and efficient tool
*/
if (!Math.prototype.getRandomValueBetween) {
Math.prototype.getRandomValueBetween = function (from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
};
}
//USAGE -- Math.getRandomValueBetween(100,1000) //950
if (!Array.prototype.getRandom) {
Array.prototype.getRandom = function () {
return this[Math.getRandomValueBetween(0, this.length - 1)];
};
}
//USAGE -- [1,34,56,76,9,67,5].getRandom();