简体   繁体   中英

Ionic get integer ID from JSON data

This should be a very simple thing to do. I am building an IONIC app with a JSON data file. The data is something like this.

[
  { "id": 1,
    "name": "John",
    "type": "male",
    "bio": "this is John"
  },
  { "id": 10,
    "name": "Mary",
    "type": "female",
    "bio": "this is Mary"
  }
]

Now I want to filter by by "type" in the data and then loop the data by "id".

<ion-list ng-repeat="person in people | filter:   {'type': 'male'}">
  <ion-item href="#tab/people/males/{{ person.id }}">{{ person.name }}
</ion-item>
</ion-list>

The Controller for this is:

.controller('PeopleController', ['$scope', '$state', '$http', function($scope, $state, $http){
$http.get('data/people.json').success(function(data){
$scope.people = data;
$scope.whichPerson = $state.params.id;
}),
}])

This displays the required data of males only by name.

However if I want to see the individual bio using the following code

<div class="card" ng-repeat="person in people | filter: { id: whichPerson }">
<h2>{{ person.name }}</h2>
<p>{{ person.bio}}</p>
</div>

When I click the individual item for each person to display person.bio I get both John and Mary.'

I figured this was because the "id" is 1 and 10 which seems to be parsing as a string to the controller. I tried putting this

"id": "1" and "id": "10"

Did not work. I did this in the controller

$scope.whichPerson = parseInt($state.params.id, 10);

This does not work either. I am totally stumped. How do I get the individual id's from the data? In fact I noticed that I can change the id to 11 or 12 or 13 etc and it still returns both records?

Any help appreciated.

Try to add the comparator :true to your filter as described in the documentation . This forces a strict comparison of the filter value instead of just checking if the data contains it.

Given the above doesn't work, you could try a custom filter by doing:

filter: { id: whichPerson }:sameID

and then in your controller:

$scope.sameID = function(actual, expected) {
        return parseInt(actual) === parseInt(expected)
    };

Even if this doesn't work, you could then at least debug within the custom filter to see where the comparison is failing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM