角。如何在控制器中过滤动态数组?

时间:2016-02-03 15:36:11

标签: angularjs angularjs-filter

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

现在我有这样的事情:

$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个colomns组成。我搜索一些东西,它只找到一行(搜索必须至少在colomn中找到一个值)。之后我添加新行。如果它包含值I,则会在表格中显示。如果我们清除搜索字段,则显示所有数据。对于这种正确的行为,我必须使用$ scope.initArray和$ scope.array进行大量的操作。如果我只使用一个数组,搜索表后包含不正确的数据。

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

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

$ scope.initArray它的初始数据(搜索之前)

1 个答案:

答案 0 :(得分:0)

有两种方法只能保留一份数据副本:

  1. 过滤模板中的数据而不是控制器中的数据
  2. 在模板中使用函数作为数据源
  3. 以下是两种方法的演示:

    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>