custom filter with Angularjs

Asked

Viewed 3,400 times

0

Talk people, I have the following problem, I have a list of names:

$scope.names=["Max", "Tom", "Ralf", "Jerry", "Snow", "Carl"];

I made a normal filter for input search

<ul>
  <li ng-repeat="name in names | filter: search">{{name}}</li>
</ul>
</div>
<div>
<input type="search" ng-model="search">
</div>

However I want to create a custom filter to show only the names related to the first letter typed in the input search, in case, type the letter "R" and the result is only "Ralf" instead of searching for the "R" in all letters, which results in "Ralf" and "Jerry".

I thought to use an angular.foreach to go through the names but I could not get the result I wanted, if it helps, follow the codepen to facilitate:

http://codepen.io/haykou/pen/aDczA

2 answers

1


Well, I found a solution as I wanted, I just did not understand the part of regex.test but I think the solution can serve other people with doubt.

var List = function($scope){
 $scope.names=["Tax", "Tom", "Ralf", "Jerry", "Snow", "Carl"];

  function escRegExp(string){
   return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g);
    }

  $scope.filterSearch = function(name) {
 if (!$scope.search){
   return true;
 }else
    var regex = new RegExp('\\b' + escRegExp($scope.search), 'i');
    return regex.test(name.split(' ')[0]);
};  
}

0

You can create a custom filter and register it at the angle.

1 - Create a module

var app = angular.module('app',[]);
<html ng-app="app">

2 - Register the controller in this module

app.controller('List',List)

3 - Create the filter

app.filter('firstType',function(){
  return function(input, type){
    var results = [];
    for(var i in input){
      var name = input[i];
        if(name[0]==type)
            results.push(name);
    }
    return results;
  };
});

4 - Calling the filter

<div ng-controller="List">
  <ul>
    <li ng-repeat="name in names | firstType: filterSearch">{{name}}</li>
  </ul> 
  <div>
    <input type="search" ng-model="filterSearch">
  </div>
</div>

Some links to help:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.