Currently, my application consists of only three small parts: a service that makes an http
call to a .json
file, a controller that receives data from the service and sends it to a view. Everything was working fine when I hard coded the data in my service.
However, once I replaced the hard coded data with a .json
file, the functionality stopped working. Even though I verified that the data was being queried correctly from the .json
file within the controller.
Here is a snippet of the simple controller code:
(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.selectItem = function(id){
myappApi.setItemId(id);
$state.go("app.item-detail");
}
};
})();
The Template code:
<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>
The service code:
(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
};
};
})();
The contents of the .json
file:
{
"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}
]
}