yontu
yontu

Reputation: 37

AngularJS doesn't display json object in html after $http.get request

I'm trying to make a get request and display the json data. Here is the html div tag where the data should be displayed:

<div ng-app="app" ng-controller="searchController">
    <ul>
        <li ng-repeat="name in datas">
            {{ name }}
        </li>
    </ul>
</div>

And here is the app:

var app = angular.module('app', [

]);

app.factory('getRequest', ($http) => {
    function get() {
        return $http.get('http://localhost:8080/imagedata/')
            .then((response) => {
                console.log(response.data);
                return response.data;
            },
            (error) => {
                return error.statusText;
            });
    }

    return {
        get: get
    }
});
app.controller('searchController', ['$scope', 'getRequest', ($scope, getRequest) => {
    $scope.datas = getRequest.get();
}]);

Inside factory I have a console.log. The data is shown in console, but not in html view. I can't explain what is happening. The code should be works fine.

Upvotes: 0

Views: 120

Answers (2)

yontu
yontu

Reputation: 37

I found the solution. As @user2864740 said, in my code I've returned the promise, not a good practice. Passing a promise into ngRepeat here is the solution

Upvotes: 0

Gerald LeRoy
Gerald LeRoy

Reputation: 1277

It's a little hard to tell what the solution is without seeing your console data. If the data ('datas') displayed in your console is an array of objects, for example something like this...

[
    {customerId: '123', name: 'Person1', city: "Toronto"}, 
    {customerId: '456', name: 'Person2', city: "Los Angeles"},
    {customerId: '789', name: 'Person3', city: "New York"}
]

you'll want to name the specific properties, like this..

<div ng-app="app" ng-controller="searchController">
    <ul>
        <li ng-repeat="item in datas">
            {{item.name}} <--------------
            {{item.customerId}} 
            {{item.city}} 
        </li>
     </ul>
</div>

Upvotes: 1

Related Questions