我正在开发一个Web应用程序,并使用AngularJS显示从REST API到模板的一组位置,我需要帮助才能让它显示在模板上。如何获取要在html模板上显示的REST数据列表?
index.html:
<!DOCTYPE html>
<html ng-app="countryApp">
<head>
<title>Angular App</title>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<!--stuff-->
<div ng-view=""></div>
<!--end stuff-->
</body>
</html>
查看/ all_locations.html
<div ng-controller="AllLocations">
<h3>Hello</h3>
<ul><li ng-repeat="location in locations"><p>{{locations.location_id}}<p></p></li><ul>
app.js文件
//app.js
var countryApp = angular.module('countryApp', ['ngRoute']);
countryApp.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'views/all_locations.html',
controller: 'AllLocations'
}).
when('/:location_id', {
templateUrl: 'views/view_location.html',
controller: 'ViewLocation'
}).
otherwise({
redirectTo: '/'
});
});
countryApp.controller('AllLocations', function ($scope, $http){
$http.get('http://localhost/slimtest2/locations').success(function(data) {
$scope.locations = data;
});
});
countryApp.controller('ViewLocation', function ($scope, $routeParams){
console.log($routeParams);
});
来自REST API的JSON数据
{ "locations" :[{"location_id":"2","location_reference":"657821349","location_title":"Guam Premier Outlet,? ???? ???"},{"location_id":"3","location_reference":"5328016947","location_title":"Underwater World,?? ?? ??"},{"location_id":"4","location_reference":"8476039215","location_title":"Fort Santa Agueda,?? ?? Agueda"},{"location_id":"5","location_reference":"5320468719","location_title":"Dulce Nombre de Maria Cathedral,Dulce? Nombre ? ??? ???"},{"location_id":"6","location_reference":"8530697412","location_title":"Leo Palace Resort,?? ??? ???"},{"location_id":"7","location_reference":"5309187462","location_title":"Fort Soledad,?? ?? ??"}]}
答案 0 :(得分:2)
尝试更改
ng-repeat="location in locations"
到
ng-repeat="location in locations.locations"
和
{{locations.location_id}}
到
{{location.location_id}}
答案 1 :(得分:1)
要在html中呈现每个值,请使用ng-repeat
指令。
这样的事情:
<body>
<!--stuff-->
<div ng-controller="AllLocations">
<div ng-repeat="location in locations">
Location Id: {{ location.location_id }} <br />
Location Reference: {{ location.location_reference }} <br />
Location Title: {{ location.location_title }}
</div>
</div>
<!--end stuff-->
</body>