angularjs: change filter options dynamically

前端 未结 3 1031
南旧
南旧 2020-12-03 19:24

What I want is something like this example in the documentation but with a unique input that can play the three roles of filtering by \"any\", \"name\" or \"phone\" properti

相关标签:
3条回答
  • 2020-12-03 19:45

    Here's another simple approach using radio buttons

    <input type="text" ng-model="search[filter]">
    
    <label>filter by these</label>
    
    <label>Any <input type="radio" ng-model="filter" ng-init="filter = '$'" value="$"></label>
    <label>name<input type="radio" ng-model="filter" value="name"></label>
    <label>phone<input type="radio" ng-model="filter" value="phone"></label>
    
    0 讨论(0)
  • 2020-12-03 19:52

    You can define ng-model like: ng-model="search[filter]" to change dynamically to which variable it should be binded (where filter is another $scope variable).

    See the fiddle: http://jsfiddle.net/lopisan/vzQKk/1/

    You have to add this line to the controller:

    $scope.search = {name:'', phone:'', $:''};
    

    And change input:

    <input type="text" ng-model="search[filter]">
    
    0 讨论(0)
  • 2020-12-03 19:54

    Here's one approach - there are probably others.

    <div ng-app>
      <div ng-controller="MainCtrl">
          <div style="background-color:#FAE8F1">
          <hr>
    
          <label>Filter</label> <input type="text" ng-model="multi"> by {{filter}}         <br>
          <ul>
          <li><a href="" ng-click="changeFilterTo('$')">Any</a></li>
          <li><a href="" ng-click="changeFilterTo('name')">By Name</a></li>
          <li><a href="" ng-click="changeFilterTo('phone')">By phone</a></li>
          </ul>
    
          <hr>
          </div>
    
          <table class="table">
            <tr><th>Name</th><th>Phone</th></tr>
            <tr ng-repeat="friend in friends | filter:getFilter()">
              <td>{{friend.name}}</td>
              <td>{{friend.phone}}</td>
            </tr>
          </table>
      </div>
    </div>
    

    Javascript:

    function MainCtrl($scope, $http) {
        $scope.friends = [{name:'John', phone:'555-1276'},
                          {name:'Mary', phone:'800-BIG-MARY'},
                          {name:'Mike', phone:'555-4321'},
                          {name:'Adam', phone:'555-5678'},
                          {name:'Julie', phone:'555-8765'}];
        $scope.filter = "$";
        $scope.multi = "";
        $scope.changeFilterTo = function(pr) {
            $scope.filter = pr; 
        }
        $scope.getFilter = function() {
            switch ($scope.filter) {
                case 'name':
                    return {name: $scope.multi};
                case 'phone':
                    return {phone: $scope.multi};
                default:
                    return {$: $scope.multi}
            }
        }
    };
    
    0 讨论(0)
提交回复
热议问题