Angular How to filter a dynamic array in the controller?

Can someone help me with a problem? nf n I have an array of objects that appears in a table and I have a search. Each object represents one row in the table. The main problem is the array. We can change it at any time (you can add new rows, delete existing rows and change the value in the table), even if we are looking for something.

Now I have something like this:

$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;
   } 
 });

As you can see, I use two arrays. Everything is fine, but when I want to change $ scope.array, I need to change $ scope.initArray. And that causes a lot of problems.

, 3 . 3 . - , ( colomn). . , , . , . $scope.initArray $scope.array. , , .

, ?

$scope.array .

$scope.initArray ( )

+4
1

:

  • ,

:

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>
Hide result
0

Source: https://habr.com/ru/post/1627171/


All Articles