我的应用目前仅是一项服务的3个小部分,它们会http
调用.json
文件控制器,该控制器将从服务中获取数据并将其发送到视图。当我对服务中的数据进行硬编码时,它运行良好。
当我将硬编码数据替换为.json
文件时,它停止工作,但是我将其记录在控制器中,并确保从.json
文件中正确查询数据。
这是简单的控制器:
(function (){
'user strict';
angular.module('myApp').controller('itemsCtrl',['$state','myappApi', itemsCtrl]);
//constructor function
function itemsCtrl($state, myappApi){
var vm = this;
myappApi.getItems(function(data){
vm.items = data;
});
//vm.items = data;
vm.selectItem = function(id){
myappApi.setItemId(id);
$state.go("app.item-detail");
}
};
})();
模板代码:
<ion-view ng-controller="itemsCtrl as vm">
<ion-content class="has-header">
<div class="list">
<a class="item item-icon-right" ng-repeat="item in vm.items" ng-click="vm.selectItem(item.id)">
<div class="row">
<div class="col item-thumbnail-left">
<img ng-src="vas-images/{{item.name}}.jpg">
</div>
<div class="col col-center">
<h3 class="blue-font">{{item.name}}</h3>
<p>{{item.desc}}</p>
</div>
<div class="col col-center">
<h4 class="blue-font-alt">Price:{{item.price}}$</h4>
</div>
</div>
<i class="icon ion-chevron-right icon-accessory"></i>
</a>
</div>
</ion-content>
</ion-view>
服务代码:
(function (){
'user strict';
angular.module('myApp').factory('myappApi',['$http', myappApi]);
function myappApi($http){
//function to get all the items.
function getItems(callback){
$http.get("app/items/data.json")
.success(function(data){
callback(data);
});
}
//function to set the item ID.
function setItemId(itemId){
currentItemId = itemId;
}
return{
getItems: getItems,
setItemId: setItemId
};
};
})();
该.json
文件:
{
"items" : [
{"id":1005, "name":"item-one", "desc":"some text here and there", "price":100},
{"id":1006, "name":"item-two", "desc":"some text here and there", "price":500},
{"id":1007, "name":"item-three", "desc":"some text here and there", "price":600},
{"id":1008, "name":"item-four", "desc":"some text here and there", "price":50},
{"id":1009, "name":"item-five", "desc":"some text here and there", "price":20},
{"id":1010, "name":"item-six", "desc":"some text here and there", "price":660}
]
}
也许您的数据有问题,因为以下内容在支持JSON文件时效果很好。
的HTML
<body ng-controller="itemsCtrl as vm">
{{ vm.items | json }}
</body>
的JavaScript
var myApp = angular.module('myApp',[]);
myApp.controller('itemsCtrl', function(myappApi){
var vm = this;
myappApi.getItems(function(response){
vm.items = response.data;
});
});
myApp.factory('myappApi', function myappApi($http){
return {
getItems: function(callback){
$http.get('data.json').then(callback).catch(callback);
}
};
});
JSON格式
[{
"name": "name",
"desc": "desc",
"price": 100
}]
相关的插件在这里http://plnkr.co/edit/NY2Un3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句