filter: notarray error in angularjs

adi picture adi · Jul 20, 2015 · Viewed 10.4k times · Source

http://plnkr.co/edit/cJsScs8ixF1aq85Ri7nV?p=preview

filter is not working. Other part of code also breaks. Throwing error filter:notarray. how it can be fixed

<head>
  <link rel="stylesheet" href="style.css">

</head>

<body ng-init="items=[3,1,2,3];">
  <h1>Hello Plunker!</h1>

  <div >

  </div>
  <input type="text" ng-model="nm" />



  <div ng-repeat="item in items track by $index | filter:nm" ng-hide="hide">
    {{item}}

  </div>

  <button ng-click="hide=!hide">Toggle </button>
  <button ng-click="items[items.length]=items.length">Add</button>


  <script src="https://code.angularjs.org/1.4.2/angular.min.js"></script>
  <script src="script.js"></script>
</body>

</html>

Answer

andyhasit picture andyhasit · Aug 30, 2015

The documentation for ng-repeat says:

track by must always be the last expression

So you need to change this line:

<div ng-repeat="item in items track by $index | filter:nm" ng-hide="hide">

to this:

<div ng-repeat="item in items | filter: nm track by $index" ng-hide="hide">

I know it's obscure, and this one catches people out. Often the documentation isn't on the page you expect it to be (e.g. filter) but is still in a logical place (e.g. ng-repeat). It 'should' all be there.