简体   繁体   English

Ionic从JSON数据获取整数ID

[英]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. 我正在使用JSON数据文件构建IONIC应用程序。 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". 现在,我想按数据中的“类型”过滤,然后按“ 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.' 当我单击每个人的单个项目以显示person.bio时,我会同时看到John和Mary。

I figured this was because the "id" is 1 and 10 which seems to be parsing as a string to the controller. 我认为这是因为“ id”分别是1和10,似乎已解析为控制器的字符串。 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? 如何从数据中获取个人ID? In fact I noticed that I can change the id to 11 or 12 or 13 etc and it still returns both records? 实际上,我注意到我可以将id更改为11或12或13等,并且它仍然返回两条记录?

Any help appreciated. 任何帮助表示赞赏。

Try to add the comparator :true to your filter as described in the documentation . 尝试按照文档中的说明将比较器:true添加到过滤器中。 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 即使这不起作用,您也可以至少在自定义过滤器中进行调试,以查看比较失败的地方

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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