【问题标题】:Angular. How can I filter dynamic array in controller?角。如何过滤控制器中的动态数组?
【发布时间】:2016-05-12 21:33:33
【问题描述】:

有人可以帮我解决问题吗?nf n 我有一个显示在表格中的对象数组,我有搜索。每个对象都是表中的一行。主要问题在数组中。我们可以随时修改它(可以添加新行、删除现有行和更改表中的值),即使我们搜索某些内容。

现在我有这样的东西:

$scope.$watch( 'search', function() {
   if($scope.search!== "") {
       if(! $scope.initArray.length) {
             $scope.initArray= $scope.array;
       }
       $scope.array= $filter('filter')($scope.initArray, function(item) {
             return item.name1.indexOf($scope.search) > -1 ||
                    item.name2.indexOf($scope.search) > -1 ||
                    item.name3.toLowerCase().indexOf($scope.search) > -1;
       });
   } else {
       $scope.array= $scope.initArray;
   } 
 });

如您所见,我使用了两个数组。一切都很好,但是当我想更改 $scope.array 时,我必须更改 $scope.initArray。它会导致很多问题。

例如,表格有 3 行。每行由 3 个列组成。我搜索一些东西,它只找到一行(搜索必须至少在其中一个列中找到值)。之后我添加新行。如果它包含我正在搜索的值,它会显示在表中。如果我们清除搜索字段,则会显示所有数据。对于这个正确的行为,我必须对 $scope.initArray 和 $scope.array 做很多相等的操作。如果我只使用一个数组,搜索表后包含不正确的数据。

有没有一种方法可以只使用一个数组?

$scope.array 我将它传递给 UI。

$scope.initArray 是初始数据(搜索前)

【问题讨论】:

    标签: angularjs angularjs-filter


    【解决方案1】:

    有两种方法可以只保留一份数据:

    1. 过滤模板中的数据,而不是控制器中的数据
    2. 在模板中使用函数作为数据源

    这是两种方法的演示:

    angular.module('filterExample', [])
    .filter('myFilter', function() {
      return function(input) {
        var output = [];
        for (var idx in input) {
          var item = input[idx];
          if (item != 'row2') {
            output.push(item.toUpperCase());
          }
        }
        return output;
      };
    })
    .controller('MyController', ['$filter', function($filter) {
      this.data = ['row1', 'row2', 'row3'];
      this.getFilteredData = function(input) {
        // here you can use this.search to filter the data
        // while keeping the original array unmodified
        return $filter('myFilter')(this.data);
      };
    }]);
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <body ng-app="filterExample">
      <h2>Initial data</h2>
      <table ng-controller="MyController as ctrl">
        <tr ng-repeat="row in ctrl.data">
          <td>{{row}}</td>
        </tr>
      </table>
      <h2>Filtered data, use filter in the template</h2>
      <table ng-controller="MyController as ctrl">
        <tr ng-repeat="row in ctrl.data | myFilter">
          <td>{{row}}</td>
        </tr>
      </table>
      <h2>Filtered data, filter data in the function</h2>
      <table ng-controller="MyController as ctrl">
        <tr ng-repeat="row in ctrl.getFilteredData()">
          <td>{{row}}</td>
        </tr>
      </table>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2016-08-07
      • 2016-01-10
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多