angularjs过滤器中的动态过滤器表达式

时间:2014-12-11 10:27:48

标签: angularjs angularjs-filter

我有一个对象说人物的数组,人物对象具有名称,年龄,性别等属性,我有一个选择从人物对象中选择属性。我想根据所选属性和文本框输入来过滤数组。

     <div ng-app="myApp" ng-controller="myCtrl" >

            <select ng-model="filterBy" ng-options=" p for p in person"  ng-init='person= ["name","age","gender"]' >  </select>

            <input type="text" ng-model="filterAs"> </input>


         <table>
       <tr>      
       <td>Name</td>
       <td>Age</td>
       <td>Group</td>
       </tr>  

       <tr  ng-repeat=" person in persons | filter:{  filterBy : filterAs   }  ">   
       <td> {{ person.Name }} </td>
       <td> {{ person.Age}} </td>
       <td> {{ person.Group}} </td>   
       </tr> 
       </table>
   </div>

2 个答案:

答案 0 :(得分:0)

以下代码应符合您的要求。 Working Demo

</head>
<body ng-app="selectExample">
  <script>
angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.colors = [
      {name:'black', shade:'dark'},
      {name:'white', shade:'light'},
      {name:'red', shade:'dark'},
      {name:'blue', shade:'dark'},
      {name:'yellow', shade:'light'}
    ];
    $scope.test=[
      {value:'name'},
      {value:'shade'}
      ]
    $scope.myColor = $scope.colors[2]; // red
    $scope.shownameandcolour=function() {

    }   
  }]);
</script>
<div ng-controller="ExampleController">



  Color (null not allowed):
  <select ng-model="myColor1" ng-options="t.value for t in test"  ng-change="shownameandcolour()"></select><br>
<br/>

  <ul> 
  <div ng-if="myColor1.value=='name'">
  <input ng-model="nameModel"><br>
    <li class="animate-repeat" ng-repeat="n in colors | filter:nameModel">
      {{n.name}}
    </li>
  </div>

    <div ng-if="myColor1.value=='shade'">
    <input ng-model="shadeModel"><br>
          <li class="animate-repeat" ng-repeat="n in colors | filter:shadeModel">
      {{n.shade}}
    </li>
    </div>
  </ul>

</div>
</html>

答案 1 :(得分:0)

希望它有所帮助 视图:

<select ng-model="key" ng-options=" key as key for (key,val) in persons[0]"  >  </select>
            <input ng-if ="key=='Name'" type="text" ng-model=search.Name> </input>
            <input ng-if ="key=='Age'"  type="text" ng-model=search.Age> </input>
            <input ng-if ="key=='Group'" type="text" ng-model=search.Group> </input>
         <table>
       <tr>
       <td ng-repeat= "p in person">{{p}}</td>
       </tr>  

       <tr  ng-repeat=" person in persons | filter:search">   
       <td> {{ person.Name }} </td>
       <td> {{ person.Age}} </td>
       <td> {{ person.Group}} </td>   
       </tr> 
       </table>

控制器:

controller("HelloController", function($scope) {

        $scope.persons=[
                        {Name:"vin",Age:"25",Group:"A"},
                        {Name:"Gok",Age:"26",Group:"B"}]
        $scope.key="Name"
        $scope.search={}