Search code examples
javascriptangularjsangularjs-directiveangularjs-ng-repeatangular-filters

Angular filter not filtering correctly in version 1.3, is it better in version 1.5?


I'm currently using the built in angular filter "$filter" in my controller to filter a dropdown list of data but the filter isn't filtering the data correctly at all. It filters it but the filtered data doesn't match the text being typed. I was reading that there may be some issues with the state of filters not working correctly in 1.3 on objects and arrays? I'm wondering if this is a version issue or if I am doing something incorrectly in my code? I'm thinking about upgrading to 1.5 so I'm just curious if my problems would be solved in 1.5 or if I have syntax errors. Here is what I have:

DATA (this is the initial data being ng-repeated over and what is being filtered:

this.items = [
            { name: 'Jim', city: 'Minneapolis', state: 'MN', zip: 44332 },
            { name: 'Boe', city: 'Scottsdale', state: 'AZ', zip: 44332 },
            { name: 'Tom', city: 'S.F.', state: 'CA', zip: 11223 },
            { name: 'Joe', city: 'Dallas', state: 'TX', zip: 34543 },
            { name: 'Jon', city: 'L.A.', state: 'CA', zip: 56433 },
        ];

TEMPLATE:

  <input type="text" class="form-control" name="inputField" ng-change="ctrl.filterTextChangeLocal($event)" ng-model="ctrl.ngModelValue" ng-click="ctrl.openDropdown($event)" />

The above input filters the list below:

  <ul class="dropdown-menu list-group" ng-if="!ctrl.ngDisabled">
    <li class="list-group-item" ng-repeat="row in ctrl.filteredItems"
    ng-mousedown="ctrl.onSelectedLocal(row, $event)">
        {{row[ctrl.itemDisplayProperty]}}
    </li>
    <li class="list-group-item text-center" ng-show="ctrl.filteredItems.length <= 0">
        {{ctrl.noResultsMessage}}
    </li>
</ul>

CONTROLLER:

     // filter the drodpown data
     //$event is being used to check for specific keypresses but doesn't matter here
     //ngModelValue is bound to ng-model inside the input

    public filterTextChangeLocal($event: ng.IAngularEvent) {
          this.filteredItems = this.$filter("filter")(this.items, this.ngModelValue);

    }

The result of above is a simple bootstrap ul dropdown list that would display a specified property on the objects in the list, here it would show the name property from the data shown above, but this data isn't correctly being filtered:

 <li>Jim</li>
 <li>Boe</li>
 <li>Tom</li>
 <li>Joe</li>
 <li>Jon</li>

Thanks


Solution

  • You should change your filter like as-

    public filterTextChangeLocal($event: ng.IAngularEvent) {
              this.filteredItems = this.$filter("filter")(this.items, {'name':this.ngModelValue});
    
        }