Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

javascript - angularjs: change filter options dynamically

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" properties, the change of role is done by an anchor click. Here is the code ready http://jsfiddle.net/ubugnu/QuyCU/ How can I update the ng-model attribute dynamically?

HTML

<div ng-app>
  <div ng-controller="MainCtrl">

      <label>Any</label> <input type="text" ng-model="search.$"> <br>
      <label>Name only</label> <input type="text" ng-model="search.name"><br>
      <label>Phone only</label> <input type="text" ng-model="search.phone"><br>

      <div style="background-color:#FAE8F1">
      <hr>

      <label>Filter</label> <input type="text" ng-model="search.$"> 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:search">
          <td>{{friend.name}}</td>
          <td>{{friend.phone}}</td>
        </tr>
      </table>
  </div>
</div>

JS

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.changeFilterTo = function(pr) {
        $scope.filter = pr; 
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...