raphael_turtle raphael_turtle - 2 months ago 13
AngularJS Question

Filter angular data by array of ids

I have a json file containing my data

[{"id":"349","title":"event 1"},{"id":"350","title":"event 2"},{"id":"351","title":"event 3"}]


A user can save events to local storage and are saved in an array

$storage.myEvents = ["349","350"]


I display all events on the page with;

<ion-item class="item-icon-right item-brown" ui-sref="detail({id: event.id})" ng-repeat="event in events track by event.id ">
<h2 class="positive"><b>{{event.title}}</b></h2>
</ion-item>


I want to show just the users events they have stored in
$storage.myEvents
but my filter doesn't work

<ion-item class="item-icon-right item-brown" ui-sref="detail({id: event.id})"
ng-repeat="event in events track by $index | filter: {id: $storage.myEvents }">


it gives the error
Error: filter:notarray Expected array but received: 0
, if I query the local storage I get

localStorage["ngStorage-myEvents"]
"["349","350"]"


if I change the filter to

filter: {id: JSON.parse($storage.myEvents)}


I still get the same error...

How can I fix this?

Answer

You can use custom filter.

  $scope.myFilter = function (e) {
    var s = $scope.$storage.myEvents;
    if (s.indexOf(e.id) != -1) return true;
    return false;
  }

  <ion-item class="item-icon-right item-brown" ui-sref="detail({id: event.id})" 
       ng-repeat="event in events | filter: myFilter track by $index">