Jonas
Jonas

Reputation: 784

AngularJS filter doesn't work

I make a fitler list of racing drivers, so you can select them on their name. I defined following filter in my view:

    <input ng-model="nameFilter" type="text" name="nameFilter" class="form-control empty" placeholder="Search Driver name...">    
<table class="col-xs-12 table table-striped">
  <thead>
    <tr><th colspan="4"></th></tr>
  </thead>
  <tbody ng-controller="driversController">
    <tr ng-repeat="driver in driversList | filter: nameFilter">
      <td>{{$index + 1}}</td>
      <td>
        <img src="img/flags/{{driver.Driver.nationality}}.png" />
        <a href="#/drivers/{{driver.Driver.driversId}}">
        {{driver.Driver.givenName}} {{driver.Driver.familyName}}
      </a>
    </td>
      <td>{{driver.points}}</td>
    </tr>
  </tbody>
</table>

This driversController is defined in my Controller.js file:

angular.module('FormulaOne.controllers', []).

  /* Drivers controller */
  controller('driversController', function($scope, F1APIservice) {


    $scope.nameFilter = null;
    $scope.driversList = [];

    //vraag 3a haal drivers op
    F1APIservice.getDrivers().success(function(response){
      //dig in the respone to get the relevant data
      $scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings;
    });


    //vraag 3b zoek filter
    $scope.searchFilter = function (driver) {
    var keyword = new RegExp($scope.nameFilter, 'i');
    return !$scope.nameFilter || keyword.test(driver.Driver.givenName) || keyword.test(driver.Driver.familyName);
};

I want to filter on the name or the firstname of a driver, but it doesn't work, the question is. How does it come?

Upvotes: 0

Views: 1855

Answers (1)

charlietfl
charlietfl

Reputation: 171669

Your input is not in same controller as the ng-repeat.

Move the ng-controller to a higher level so the ng-model and filter are in same scope

<div ng-controller="driversController">
    <input ng-model="nameFilter">    
    <table>
      <thead>
        <tr><th colspan="4"></th></tr>
      </thead>
      <tbody>
        <tr ng-repeat="driver in driversList | filter: nameFilter">
         <td>.....
        </tr>
       </tbody>
    </table>
</div>

Upvotes: 2

Related Questions