Search code examples
javascriptangularjsangularjs-ng-repeatangular-filters

Filter ng-repeat according to the first letter


In AngularJS, I have an array of Objects. I want to display data filtered for the first letter. I used the following way. HTML:

<p ng-repeat="film in filmList | startsWith:'C':'title'">{{film.title}}</p>

JS:

.filter('startsWith', () => {
    return (items: any, prefix: any, itemProperty: any) => {
        if (items && items.length) {
            return items.filter((item: any) => {
                var findIn = itemProperty ? item[itemProperty] : item;
                return findIn.toString().indexOf(prefix) === 0;
            });
        }
    };
});`

And it works. But now my target is to filter (always for the first letter) based on two choices. For example, filter movies whose title begins for 'B' or 'C'.

I've written the following code, but it doesnt work:

HTML:

 <p ng-repeat="film in filmList | startsWith:'[B, C]':'title'">{{film.title}}</p>

JS:

.filter('startsWith', () => {
    return (items: any, prefixes: any, itemProperty: any) => {
        if (items && items.length) {
        return items.filter((item: any) => {
            var findIn = itemProperty ? item[itemProperty] : item;
            for(let i = 0; i < prefixes.length; i++){
                return findIn.toString().indexOf(prefixes[i]) === 0;
            }
        });
    }
    };
 });

Solution

  • parameter '[B, C]' will be recognized as string not array. You shall define array in controller and transform it.

    UPD:

    when you invoke return in for-loop, the loop will break. I have make some change to avoid this.

    refer below code snippet(updated).

    var app = angular.module("app", [])
    app.controller("myCtrl", function($scope) {
      $scope.filmList = [{
          title: 'Black'
        },
        {
          title: 'Brown'
        },
        {
          title: 'Clown'
        },
        {
          title: 'Red'
        },
        {
          title: 'Gray'
        }
      ];
      $scope.option = ['B', 'C'];
    })
    app.filter('startsWith', () => {
      return (items, prefixes, itemProperty) => {
        if (items && items.length) {
          return items.filter((item) => {
            var findIn = itemProperty ? item[itemProperty] : item;
            
            for (let i = 0; i < prefixes.length; i++) {
              if (findIn.toString().indexOf(prefixes[i]) === 0) {
                return true;
              }
            }
          });
        }
      };
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <div ng-app="app" ng-controller="myCtrl">
      <p ng-repeat="film in filmList | startsWith:option:'title'">{{film.title}}</p>
    </div>