如何根据从 json 文件传递的 id 更改数据。 JSON:
{
"hotels": [
{
"id" : 1,
"name": "some hotel 1",
"category" : [{
"id" : 1,
"hotel_id" : 1,
"name" : "Cat name 1",
"bnb" : "yes",
"simple" : "yes"
}]
},
{
"id" : 2,
"name": "some hotel 2",
"category" : [{
"id" : 1,
"hotel_id" : 2,
"name" : "Cat name 1",
"bnb" : "yes",
"simple" : "yes"
}]
}
]
}
在我的 html 中,我有 ng-repeat ,例如:
<p>Hotel names</p>
<ul>
<li ng-repeat="hotel in list.hotels">
{{hotel.name}}
<ul class="thumbnails">
<p>Category</p>
<li ng-repeat="cat in hotel.category">
{{cat.name}}
</li>
</ul>
</li>
</ul>
因此,这将显示该 json 文件中的所有内容,并且我试图将其限制为仅显示一家酒店的数据(我知道我可以使用 {{hotel[0] .name}}
),但必须有更好的方法,以及如何通过按下按钮来使用某种开关来显示同一 div 中 id 1 的酒店到 id 2 的酒店的数据,反之亦然。反之亦然?
谢谢。
最佳答案
您可以使用 ng-repeat
创建链接来根据点击显示酒店,如以下演示或此 fiddle 所示。 .
对于类别,您可以使用另一个ng-repeat
(演示中未添加)。
angular.module('demoApp', [])
.controller('mainController', MainController);
function MainController() {
this.hotels = [
{
"id" : 1,
"name": "some hotel 1",
"category" : [{
"id" : 1,
"hotel_id" : 1,
"name" : "Cat name 1",
"bnb" : "yes",
"simple" : "yes"
}]
},
{
"id" : 2,
"name": "some hotel 2",
"category" : [{
"id" : 1,
"hotel_id" : 2,
"name" : "Cat name 1",
"bnb" : "yes",
"simple" : "yes"
}]
}
];
this.selectedHotel = this.hotels[0];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController as mainCtrl">
<a href="#" ng-repeat="hotel in mainCtrl.hotels" ng-click="mainCtrl.selectedHotel = hotel">{{hotel.name}}</a>
<div>
Hotel name: {{mainCtrl.selectedHotel.name}}
Category: {{mainCtrl.selectedHotel.category}}
</div>
</div>
关于javascript - AngularJS 根据 id 显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36072749/