Gobinath M
Gobinath M

Reputation: 2021

How to pass ng-repeat value to controller

I am using an ng-repeat directive with filter like so:

<div ng-repeat="person in data">
</div

i.e Showing {{data.length}} Persons. (I am expect to pass the length value to controller)

But i need to pass the filtered length value to controller because i do same logic based on the filtered length value.

Upvotes: 1

Views: 1053

Answers (1)

Muhsin Keloth
Muhsin Keloth

Reputation: 7954

1.Method 1

ng-repeat="item in filtered = (data | filter:filterExpr)"

Would create the filtered list.

filtered.length will show the filtered length.

2.Method 2

Use $watch for detecting the filtered length.

$scope.length = $scope.data.length;
$scope.$watch("search", function(query) {
    $scope.length = $filter("filter")($scope.data, query).length;
});

Example

var app = angular.module('angularjs-starter', [])

app.controller('MainCtrl', function($scope, $filter) {
  $scope.data = [{
    "name": "Martin",
    "age": 21
  }, {
    "name": "Peter",
    "age": 26
  }, {
    "name": "Arun",
    "age": 25
  }, {
    "name": "Maxwell",
    "age": 22
  }];

  $scope.counted = $scope.data.length;
  $scope.$watch("search", function(query) {
    $scope.filteredData = $filter("filter")($scope.data, query);
  });

});
<html ng-app="angularjs-starter">

<head lang="en">
  <meta charset="utf-8">
  <title>Demo</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
  <link rel="stylesheet" href="style.css">
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <input ng-model="search" type="text">
  <br>Showing {{data.length}} Persons;
  <br>Filtered {{filteredData.length}}
  <ul>
    <li ng-repeat="person in filteredData">
      {{person.name}}
    </li>
  </ul>

</body>
<script>
</script>

</html>

Upvotes: 2

Related Questions