我对angularJs很新。
我正在尝试根据url参数检索对象。
例如,我有以下代码:
var tripApp = angular.module('tripApp', ['ui.state', 'ui.bootstrap', 'restangular', 'tripApp.directives', 'restaurantServices'])
tripApp.config(function($stateProvider, $urlRouterProvider, RestangularProvider){
RestangularProvider.setBaseUrl('json');
RestangularProvider.setRequestSuffix('.json');
$urlRouterProvider.otherwise("/hotels")
$stateProvider
.state('hotels', {
url: "/hotels/:id",
templateUrl: "templates/hotels.html",
controller: "HotelDetailController"
})
我的控制器为:
tripApp.controller('HotelDetailController', function($scope, $timeout, Restangular) {
});
如果我的json文件是:
,我如何能够根据字段'url'检索记录?{
"hotels":
[
{
"url":"bandos-island-resort",
"name": "Bandos Island",
"city": "Male",
"country": "Maldives",
"img": "http://www.barcelo.com/BarceloHotels/en_GB/Images/oviedo-barcelo-hotels-views.jpg21-29254.jpg",
"price": 199,
"offer": 50,
"standard": [1, 2, 3, 4],
"roomsleft": 4,
"facilities": [
{
"wifi": true,
"breakfast": false,
"spa": false,
"beachAccess": false,
"pool": false,
"airportShuttle": false,
"restaurant": false,
"bar": false,
"coffeeShop": false,
"noSmoking": false,
"petFriendly": false,
"jacuzzi": false,
"laundry": true,
"miniBar": false,
"parking": false,
"roomService": false,
"sauna": false,
"scubaDiving": false,
"snorkeling": false,
"waterSkiing": false,
"windSurfing": false,
"tennis": false,
"golf": false,
"weddingPlan": false
}
]
},
{
"url":"bandos-island-resort",
"name": "Club Faru",
"img": "http://www.barcelo.com/BarceloHotels/en_GB/Images/oviedo-barcelo-hotels-views.jpg21-29254.jpg",
"price": 299,
"offer": 0,
"standard": [1, 2, 3],
"roomsleft": 4,
"facilities": [
{
"wifi": true,
"breakfast": false,
"spa": false,
"beachAccess": false,
"pool": false,
"airportShuttle": false,
"restaurant": false,
"bar": false,
"coffeeShop": false,
"noSmoking": false,
"petFriendly": false,
"jacuzzi": false,
"laundry": false,
"miniBar": false,
"parking": false,
"roomService": false,
"sauna": false,
"scubaDiving": false,
"snorkeling": false,
"waterSkiing": false,
"windSurfing": false,
"tennis": false,
"golf": false,
"weddingPlan": false
}
]
}
]
}
我能够检索整个文件并重复数据,但我想基于url字段过滤记录并在我的视图中使用它。任何帮助,将不胜感激。感谢
答案 0 :(得分:1)
您要找的是service $routeParams。从文件或AJAX请求获取数据后,使用$ routeParams.id在路由中获取:id。
这是一个非常简单的示例(from fiddle)
<div ng-app="myApp">
<div ng-view></div>
<script type="text/ng-template" id="/page.html">
My ID is: {{id}}
</script>
</div>
app.js
var app = angular.module('myApp', [])
.config(function($routeProvider) {
$routeProvider
.when('/page/:id', {templateUrl: '/page.html', controller: 'PageController'})
.otherwise({redirectTo:'/page/50'});
}).controller('PageController', function($scope, $routeParams) {
$scope.id = parseInt($routeParams.id);
});