Faizuddin Mohammed
Faizuddin Mohammed

Reputation: 4328

Unable to reference filtered array in ngRepeat - AngularJS

I have an ngRepeat directive that is filtered as:

<li ng-repeat='item in items | filter:searchTerm as filteredItems'>{{item.name}}</li>

I am tring to access the filteredItems in my controller like $scope.filteredItems but I'm getting an undefined. How should I solve this?

I have nested controllers. Is the problem with $scope?

My controllers are something like this in my view:

<div ng-controller='MainController'>
 <div ng-controller='FilterController'>
  <li ng-repeat='item in items | filter:searchTerm as filteredItems'>{{item.name}}</li>
 </div>
</div>

I'm trying to access $scope.filteredItems in FilterController.

Upvotes: 0

Views: 56

Answers (1)

Grundy
Grundy

Reputation: 13381

You can use assigning in ng-repeat expression like ng-repeat='item in filteredItems = (items | filter:searchTerm)'
NOTE: in comment was wrong variant, because assigning more priority than pipe.

var appModule = angular.module('app', []);
appModule.controller('MainController', function ($scope) {
    //some functions and variables here
    $scope.items = [
        {name:'1234'},
        {name:'2341'},
        {name:'3412'},
        {name:'4123'},
        {name:'4321'}
    ];
});
appModule.controller('FilterController', function ($scope) {
    
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.js"></script>
<div ng-app="app" ng-controller='MainController'>
    <div ng-controller='FilterController'>
        <!-- FilterController has many filters that are not related -->
        <input type="text" ng-model="searchTerm" />
        <ul>
            <li ng-repeat='item in filteredItems = (items | filter:searchTerm)'>{{item.name}}</li>
        </ul>
        {{filteredItems}}
    </div>
</div>

but seems that better filter in controller:

var appModule = angular.module('app', []);
appModule.controller('MainController', function ($scope) {
    //some functions and variables here
    $scope.items = [
        {name:'1234'},
        {name:'2341'},
        {name:'3412'},
        {name:'4123'},
        {name:'4321'}
    ];
});
appModule.controller('FilterController', function ($scope,$filter) {
    var filter = $filter('filter');
    $scope.filter = function(){
      $scope.filteredItems = filter($scope.items, $scope.searchTerm);
    }
    $scope.filter();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.js"></script>
<div ng-app="app" ng-controller='MainController'>
    <div ng-controller='FilterController'>
        <!-- FilterController has many filters that are not related -->
        <input type="text" ng-model="searchTerm" ng-change="filter()" />
        <ul>
            <li ng-repeat='item in filteredItems'>{{item.name}}</li>
        </ul>
        {{filteredItems}}
    </div>
</div>

Upvotes: 1

Related Questions