从字符串的开头滤波器纳克-重复元件 [英] Filter ng-repeat elements from the beginning of the string
问题描述
我和AngularJS试验,这是我第一次尝试。我试图像,而不是包含,开头过滤使用的东西对象的数组,但我不理解如何做到这一点。
I'm experimenting with AngularJS, this is my first try. I'm trying to filter an array of objects using something like "starts with" rather than "contains", but I'm not understanding how to do that.
让我们说,我有一个元素
阵列像这样
Let's say that I have an elements
array like this
[{
amount: 50
}, {
amount: 25
}]
如果我想通过 5
过滤两个记录将显示,而我只是想有第一个,以启动一5
。
If I want to filter by 5
both records will be shown, while I just want to have the first one, the one that starts with 5
.
这是我到目前为止已经完成,为循环的一部分(我还添加了排序和分页一部分,即使或许没有影响到我想要实现)
This is what I've done so far, for the looping part (I've also added the ordering and paging part, even if maybe isn't influencing what I'm trying to achieve)
<tr ng-repeat="element in elements | filter:search:strict | orderBy:predicate:reverse | filter:startFrom:currentPage*pageSize | limitTo:pageSize">
<td>{{element.name}}</td>
<td>{{hotel.amount}}</td>
</tr>
和在那里我写输入 5
<input class="pull-right" ng-model="search.amount">
我不理解如何在这里创建一个自定义的处理程序,这样我可以分析每个第n项,看看它是否与传递的数字开始。
I'm not understanding how to create a custom handler here, so that I can parse each nth item and see if it starts with the passed number.
推荐答案
我只写基本的自定义过滤器:
I would just write basic custom filter:
JS
var iApp = angular.module("App", []);
iApp.filter('myfilter', function() {
function strStartsWith(str, prefix) {
return (str+"").indexOf(prefix) === 0;
}
return function( items, amount) {
var filtered = [];
angular.forEach(items, function(item) {
if(strStartsWith(item.amount, amount)){
filtered.push(item);
}
});
return filtered;
};
});
iApp.controller('TestController', function($scope)
{
$scope.amount='';
$scope.elements = [
{ amount: 50},
{ amount: 25 }];
});
HTML
<body data-ng-controller="TestController">
<input class="pull-right" ng-model="amount">
<table id="hotels">
<tr data-ng-repeat="element in elements | myfilter:amount">
<td>{{element.amount}}</td>
</tr>
</table>
<br/>
</body>
演示<大骨节病> Plunker < /骨节病>
Demo Plunker
这篇关于从字符串的开头滤波器纳克-重复元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!