背景:我正在做一個關於紐約地鐵的簡單離子項目。我正在使用離子「標籤」模板,並且我有一個標籤,其中列出了所有路線及其符號(1,2,3,A,C,E等),用戶應該能夠點擊任何在那裏列出的路線並被帶到一個詳細頁面(有點像當你開始一個新的離子項目時他們在標籤模板中有一個「聊天/聊天詳細信息」設置)。對象沒有從離子服務得到正確返回
問題是我似乎無法獲得路線詳細信息頁面加載有關所選路線的信息。像{{route.name}}
和{{route.desc}}
這樣的表達式變爲空白。
routes.json文件(樣品,www/js/routes.json
提交下):
{
"routes": [{
"id": "1",
"name": "1",
"desc": "7 Avenue Local",
"className": "c123"
},
{
"id": "2",
"name": "2",
"desc": "7 Avenue Express",
"className": "c123"
},
{
"id": "3",
"name": "3",
"desc": "7 Avenue Express",
"className": "c123"
},
...
app.js:
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
// ...
.state("tab.routes", {
url: "/routes",
views: {
"tab-routes": {
templateUrl: "templates/tab-routes.html",
controller: "RoutesCtrl"
}
}
})
.state("tab.route-detail", {
url: "/routes/:id",
views: {
"tab-routes": {
templateUrl: "templates/route-detail.html",
controller: "RouteDetailCtrl"
}
}
});
controllers.js:
angular.module('starter.controllers', [])
// ...
/* This one works perfectly */
.controller('RoutesCtrl', function($scope, $http) {
$http.get("js/routes.json").then(function(response) {
$scope.routes = response.data.routes;
console.log($scope.routes);
});
})
/* This one does NOT work */
/* $stateParams.id returns the correct value, but $scope.route
does not store the Route returned from the service (null) */
.controller("RouteDetailCtrl", function($scope, $stateParams, Routes) {
$scope.route = Routes.getRoute($stateParams.id);
})
services.js:
angular.module('starter.services', [])
/* This is the problem */
.factory("Routes", function($http) {
return {
getRoute: function(id) {
return $http.get("js/routes.json").then(function(response) {
var routes = response.data.routes;
for(var i = 0; i < routes.length; i++) {
if(parseInt(id) === parseInt(routes[i].id)) {
return routes[i];
}
}
return null;
})
}
}
})
我認爲這個問題與JSON返回services.js
的方式有關 - 是我的JSON存儲方式,還是我在接收端「解析」它的方式? 「RoutesCtrl」工作得很好,但我似乎無法獲得路線細節工作,無論我在services.js
中使用response
的哪種變化 - 我嘗試過response
,response.data
,response.data.routes
,沒有任何工作。
route-detail.html :(如您所見,{{route.whatever}}引用controllers.js
中的$ scope.route,但它沒有被存儲)。
<ion-view view-title="{{route.name}}">
<ion-content class="padding">
<h2>{{route.name}}</h2>
<h2>{{route.desc}}</h2>
<p>This is the detail page.</p>
</ion-content>
</ion-view>