简体   繁体   中英

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. 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. Using the default angular filter I am able to pass ng-model into it like this:

<input type="text" ng-model="searchID">

<div ng-repeat="additive in additives | filter:searchID">

But when I try do this with my exactMatch filter

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.

I also realise that ng-repeat might not be the best way to do this since I am only ever returning max 1 object.

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;
        }
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM