Accessing filtered results

Hi all,

I am unable to access the filter array I am passing the result of an ng-repeat into.My code looks like below, with the intention of being able to access the filtered array both in the HTML and the controller for other uses.

index.html:

<li ng-repeat="item in filtered = (items | filter:input.searchInput)"><h4>{{item.title}}</h4><p>{{item.content}}</p></li>
<p>{{filtered.length}} matches found</p>

app.js

.state('main.itemsPage', {
  url: "/items",
  views: {
    'itemsContainer':{
      templateUrl: "templates/items.html",
      controller: "itemsCtrl",
      resolve:{
        items:[ '$http', function($http){
          return $http.get('http://localhost/itemsTest/items.json').then(function(response){
            return response.data;
          })
        }]
      }
    }
  }
})

controller.js

.controller('itemsCtrl', function($scope, $state, items, $ionicScrollDelegate){
  $scope.input = {};
  $scope.items= items;
  console.log($scope.filtered)
}

The last line (console.log) returns undefined, and the binding in the index file to get the length of the array also yields nothing

Are you aware of anything that needs to be taken into consideration to make the filtered array accessible?

1 Like

UPDATE: the binding seems to be working now, but still unable to see the array in the controller with $scope.filtered

Hi,

In my experience, i never initialize controller in my state (config state) if you had

.state('app', {
 url: '/app',
 views: {
  templateUrl: 'template/item.html',
  controller: 'itemsCtrl'
 }
}

)

if you do that, your view will execute first then your controller and last your model, so the steps are :

  • generate views
  • call controller
  • init model

it’s very normal if your $scope is not displayed in your views, because $scope will be ‘undefined’ like i mentioned before, views will called at the first time. so, views can’t read $scope and will result blank or 'undefined’
we have 2 options to resolve this,

  1. like you have to do, using resolve in state
  2. call controller on top of views <-- i always use it

you already had for option 1, so i’ll explain option 2

in your state,

.state('app', {
 url: '/app',
 views: {
  templateUrl: 'template/item.html',
 }
}

and in your views (item.html)

<div ng-controller="itemsCtrl">
 <!-- call your $scope here -->
</div>

for example,
controller: itemsCtrl.js

angular.module('myapp').controller('itemsCtrl', function($scope) {
 $scope.filtered = {
  title: 'test',
  content: 'abc'
 };
});

views: item.html

<div ng-controller="itemsCtrl">

<select ng-model="filterBy.myItem">
    <option value="">All</option>
    <option value="test">Test</option>
 </select>

 <ul>
<li ng-repeat="item in filtered | filter: {item: filterBy.myItem}"><h4>{{item.title}}</h4><p>{{item.content}}</p</li>
</ul>
</div>

i hope it’s works,

Sincerely,
Donny

1 Like