使用从 API 返回的数据创建有序列表
Create ordered list using data returned from API
我遵循了很多关于此的教程,但无法正常工作。我想创建一个有序列表,其中包含通过 API 接收到的经过处理的数据。我为我需要询问的每个 WebService 创建了一个工厂。
工厂:
angular.module('aparcare').factory('Items', function ($http) {
return {
get: function (fields) {
return $http({
method: "POST",
url: "the-url-to-the-api",
data: "field=2&anotherfield=4",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
return response.data.Items;
}, function (error) {
console.log(error);
});
}
}
});
控制器:
angular.module('app').controller('ItemController', function ($http, $rootScope, $window, $scope, Items) {
var controller = this;
controller.items = [];
//Call the API
Items.get().then(function (response) {
//Transform array of objects in associative id => object
angular.forEach(response, function (item) {
controller.items[item.ID] = item;
});
}, function (error) {
console.log("Error ocurred on API call");
});
});
模板:
<ul class="dropdown-menu" role="menu" id="select-entity">
<li ng-repeat="item in controller.items">
<a ng-click="controller.select_item(item.ID)">{{ item.DESCRIPTION }}</a>
</li>
</ul>
目前日志的顺序是1 3 2
而不是1 2 3
您不需要创建关联数组。
Items.get().then(function (items) {
//Assign items directly
controller.items = items;
}, function (error) {
});
我遵循了很多关于此的教程,但无法正常工作。我想创建一个有序列表,其中包含通过 API 接收到的经过处理的数据。我为我需要询问的每个 WebService 创建了一个工厂。
工厂:
angular.module('aparcare').factory('Items', function ($http) {
return {
get: function (fields) {
return $http({
method: "POST",
url: "the-url-to-the-api",
data: "field=2&anotherfield=4",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
return response.data.Items;
}, function (error) {
console.log(error);
});
}
}
});
控制器:
angular.module('app').controller('ItemController', function ($http, $rootScope, $window, $scope, Items) {
var controller = this;
controller.items = [];
//Call the API
Items.get().then(function (response) {
//Transform array of objects in associative id => object
angular.forEach(response, function (item) {
controller.items[item.ID] = item;
});
}, function (error) {
console.log("Error ocurred on API call");
});
});
模板:
<ul class="dropdown-menu" role="menu" id="select-entity">
<li ng-repeat="item in controller.items">
<a ng-click="controller.select_item(item.ID)">{{ item.DESCRIPTION }}</a>
</li>
</ul>
目前日志的顺序是1 3 2
而不是1 2 3
您不需要创建关联数组。
Items.get().then(function (items) {
//Assign items directly
controller.items = items;
}, function (error) {
});