Search code examples
angularjsangular-filters

AngularJS scope variable for object in filter


I'm trying to change which property I'm filtering by assigning the property name to a variable, but it's not working. Is there a way to accomplish this without writing my own filter? codepen

<div ng-app="app" ng-controller="main as m">
  <input ng-model="keyword"/>
  <p>Property: {{m.property}}</p> <!-- resolves to 'name' -->
  <!-- does not work-->
  <div ng-repeat="o in m.objects | filter:{m.property:keyword}">
    {{o.name}}
  </div>
  <hr/>
  <!-- works-->
  <div ng-repeat="o in m.objects | filter:{name:keyword}">
    {{o.name}}
  </div>
</div>

Solution

  • If I understand your question right, I think this is what you are looking for.

    Relevant code:

    HTML:

    <select ng-model="property" ng-change="clearSearch()">
      <option>name</option>
      <option>age</option>
      <option>city</option>
    </select>
    
    <input ng-model="search[property]" />
    
    <div class="box">
      <div class="item" ng-repeat="item in data | filter:search">
        {{item.name}} | {{item.age}} | {{item.city}}
      </div>
    </div>
    

    Javascript:

    var app = angular.module("myapp", []);
    app.controller("main", function($scope){
      $scope.search = {};
      $scope.clearSearch = function(){
        $scope.search.name = "";
        $scope.search.age = "";
        $scope.search.city = "";
      }
      $scope.property = "name";
      $scope.data = [
          {
            name: "Robert",
            age: 23,
            city: "Orem"
          },
          {
            name: "Alice",
            age: 44,
            city: "Nephi"
          },
          {
            name: "Susan",
            age: 12,
            city: "Odgen"
          },
          {
            name: "Henry",
            age: 63,
            city: "South Jordan"
          },
          {
            name: "Frank",
            age: 35,
            city: "Provo"
          },
          {
            name: "Albert",
            age: 32,
            city: "Payson"
          },
      ];
    });