javascript - AngularJS 根据 id 显示值

标签 javascript angularjs json

如何根据从 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/

相关文章:

javascript - 在移动设备上查看固定标题

json - 如何覆盖 Ext JS JsonStore 超时?

python - 如何使用 Python 中的键访问 JSON 字符串中的值?

javascript - 检索 json 数组中具有相同 id 的对象 (javascript)

javascript - HTML5 - 超时后在 Canvas 上绘制

javascript - 如何从 AJAX 请求中解析 HTML?

javascript - 使用存储的凭据自动登录 PhoneGap Onsen UI 应用程序

javascript - 单击时将数据绑定(bind)到 Controller

javascript - ScrollSpy 与脚本添加了 id

javascript - 纯CSS下拉菜单点击隐藏还是显示div?