[英]Pass ng-model into a custom filter
I need to make a text box that searches through a javascript array (with objects in it) using angular. 我需要制作一个文本框,该文本框使用angular搜索遍历javascript数组(包含对象)。 It needs to be strict and only return a result once it is exactly matched (So unlike the default filter, if there is no text nothing should be returned).
它必须严格,并且仅在完全匹配后才返回结果(因此与默认过滤器不同,如果没有文本,则不返回任何内容)。 I found a custom filter on here (thanks guys), that did what I wanted with one exception: I cant pass my input ng-model to it.
我在这里找到了一个自定义过滤器(谢谢大家),除了一个例外,它实现了我想要的功能:我无法将输入的ng-model传递给它。 Using the default angular filter I am able to pass ng-model into it like this:
使用默认的角度过滤器,我可以像这样将ng-model传递给它:
<input type="text" ng-model="searchID">
<div ng-repeat="additive in additives | filter:searchID">
But when I try do this with my exactMatch filter 但是当我尝试使用我的compareMatch过滤器执行此操作时
app.filter('exactMatch', function() {
return function(additives, pattern) {
var result = [];
console.log(pattern);
additives.forEach(function (additive) {
if(pattern != "") {
console.log(pattern);
if (additive.Number == pattern) {
result.push(additive);
}
}
});
return result;
}
});
It refuses to cooperate, and that console.log(pattern)
returns undefined. 它拒绝合作,并且
console.log(pattern)
返回undefined。
I also realise that ng-repeat
might not be the best way to do this since I am only ever returning max 1 object. 我也意识到
ng-repeat
可能不是最好的方法,因为我只返回过1个对象。
You can try removing the filter completely and just showing/hiding elements if they are equal. 您可以尝试完全删除过滤器,如果相等则仅显示/隐藏元素。
Markup: 标记:
<div ng-app="app" ng-controller="mainCtrl">
<input type="text" ng-model="search.searchId">
<div ng-repeat="additive in data.additives">
<span ng-show="actions.showIfEqual(additive);">{{additive}}</span>
</div>
</div>
Controller logic: 控制器逻辑:
app.controller('mainCtrl', function($scope) {
$scope.data = {
additives: ['a','b', 'c', 'd']
}
$scope.search = {
searchId: ''
};
$scope.actions = {
showIfEqual: function (additive) {
console.log(additive === $scope.search.searchId);
return additive === $scope.search.searchId;
}
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.