Lloople
Lloople

Reputation: 1844

Create ordered list using data returned from API

I followed a lot of tutorials about this but can't have this working. I want to create an ordered list with a manipulated data received via API. I create a factory for each WebService I need to ask.

Factory:

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);
            });
        }
    }
});

Controller:

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");
    });
});

Template:

<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>

Currently the order of logs are 1 3 2 not 1 2 3

Upvotes: 2

Views: 636

Answers (1)

Satpal
Satpal

Reputation: 133403

You don't need to create an associative array.

Items.get().then(function (items) { 
    //Assign items directly
    controller.items = items;
}, function (error) {

});

DEMO

Upvotes: 3

Related Questions