是资源概念的新手,并且我只是试图从嵌套的json中获取数据时遇到了这段代码。我有我的工厂方法,能够获取数据,并在控制台的响应头中。但我无法检索它进行打印。
var f = angular.module("FactModule", ['ngResource']);
f.factory("MenuFactory", function($resource){
var menuitems =[];
var menuResource =[];
var menuResource = $resource("http://localhost:3000/items/:id", {"id":"@mid"},{myupdate:{method: "PUT"}})
return {
getMenuItems: function(){
menuitems = menuResource.get();
console.log(menuitems);
},
}
})
这是我的json
{
"items":
{
"wsmenuitems": [
{
"code": "AB201",
"name": "ABCD",
"price": "20.5",
"description": "ABCD",
"id": 2
},
{
"code": "901",
"name": "XYZ",
"price": "25",
"description": "XYZ,
"id": 5
}
],
"wsorderitems": [
{
"code": "AB201",
"name": "XYA",
"price": "20.5",
"description": "XYA",
"id": 2
},
{
"code": "901",
"name": "PQR",
"price": "25",
"description": "PQR",
"id": 5
}
]
}
}
这是我的控制器:
c.controller("MenuController", function($scope, MenuFactory){
$scope.itemsList = MenuFactory.getMenuItems();
});
HTML:
<tr ng-repeat="menuitem in itemsList">
<td>{{$index}}.{{menuitem.name}}</td>
<td>{{menuitem.price}}</td>
<td><button class="btn btn-primary" ng-click="placeOrder(menuitem)" ng-disabled="itemAdded($index)">Order <i class="glyphicon glyphicon-shopping-cart"></i></button></td>
</tr>
答案 0 :(得分:0)
在您的代码中,您不会从工厂返回任何内容。请参阅jsfiddle example。
var f = angular.module("FactModule", ['ngResource']);
f.factory("MenuFactory", function ($resource) {
var menuitems = [];
var menuResource = [];
var menuResource = $resource("http://localhost:3000/items/:id", {
"id": "@mid"
}, {
myupdate: {
method: "PUT"
}
})
return {
getMenuItems: function () {
return menuResource.get().$promise;
},
}
})
控制器代码
MenuFactory.getMenuItems().then((data) => {
$scope.itemsList = data;
}).catch((err) => {
console.log(err);
})