【问题标题】:How to bind two ng-models values together如何将两个 ng-models 值绑定在一起
【发布时间】:2018-03-20 22:29:49
【问题描述】:

我有一个显示为表格的 JSON 文件,我想使用两个步骤在此表格中进行搜索:

  1. 从选择菜单中选择一个选项以选择要在哪一列中搜索。

  2. 输入,用于输入要搜索的关键字。

那么如何将“selected option form select tag”的值与“input”的值连接起来呢?

例如,用户从选择菜单中选择了选项“姓名”,然后他在输入中输入了“约翰”

这是我的代码:

https://jsfiddle.net/p1nkfpez/7/

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
    $scope.selection = "nm";
    $http.get("https://api.myjson.com/bins/i9h1v")
    .then(function(response) {
        $scope.myRows = response.data;
        $scope.rowsStatus = response.status;
        $scope.rowsStatusText = response.statusText;
     });
});

我希望 Angular 过滤器是这样的: 过滤器:keyword.selection

【问题讨论】:

  • 尝试将“row in myRows | filter:keyword:false:selection”放入 data-ng-repeat

标签: angularjs angular-filters


【解决方案1】:

您可以创建一个函数来动态创建过滤器对象:

$scope.getFilter = function() {
    return {
        [$scope.selection]: $scope.keyword
    }
}

并像这样使用它:

<tr data-ng-repeat="row in myRows | filter:getFilter()">
    ...
</tr>

【讨论】:

    【解决方案2】:

    您可以创建一个自定义过滤器,您可以在其中按名称访问您的属性。

    自定义过滤器

    $scope.myCustomFilter = function(row){
      if($scope.keyword == undefined || $scope.keyword.length == 0)
        return true;
      if(row[$scope.selection].toLowerCase().indexOf($scope.keyword) >= 0){
        return true;
      }
      else
        return false;
    }
    

    并将过滤器添加到您的 ng-repeat

    <tbody>
      <tr data-ng-repeat="row in myRows | filter: myCustomFilter">
        <td>{{$index + 1}}</td>
        <td>{{row.nm}}</td>
        <td>{{row.cty}}</td>
        <td>{{row.hse}}</td>
        <td>{{row.yrs}}</td>
      </tr>
    </tbody>
    

    Updated Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-21
      • 2011-08-09
      • 2016-12-29
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      相关资源
      最近更新 更多