azium
azium

Reputation: 20614

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>

Upvotes: 0

Views: 3397

Answers (3)

Trevor
Trevor

Reputation: 13437

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"
      },
  ];
});

Upvotes: 2

maxisam
maxisam

Reputation: 22705

In short, <div ng-repeat="o in m.objects | filter:{m.property:keyword}"> {m.property:keyword} is not a correct expression

Upvotes: 1

j.hwang
j.hwang

Reputation: 1

Have you tried filter without the "m." in "m.property"?

<div ng-repeat="o in m.objects | filter:{property:keyword}">

Upvotes: 0

Related Questions