Search code examples
javascriptangularjsgetjsoncodeigniter-3

Need help fetching data JSON to scope AngularJS


i am newbie at AngularJS and in now trying to learn it. This time i am learning how to create one page app using codeigniter and angular with RESTful lib.

I have JSON like this :

[{"id":"25","title":"abc","description":"sss"},{"id":"26","title":"sd","description":"sdsd"}]

i just cannot fetch it to $scope with ng-repeat working no matter what i do. This is my function :

$http.get('Api/items').then(function(response)
        {       
            $scope.items = response;
            console.log(response);
        });

and this is my table view :

<table class="table table-bordered pagin-table">
<thead>
    <tr>
        <th>No</th>
        <th>Title</th>
        <th>Description</th>
        <th width="220px">Action</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="x in items">
        <td>{{ $index + 1 }}</td>
        <td>{{ x.title }}</td>
        <td>{{ x.description }}</td>
        <td>
            <button data-toggle="modal" ng-click="edit(x.id)" data-target="#edit-data" class="btn btn-primary">Edit</button>
            <button ng-click="remove(x,$index)" class="btn btn-danger">Delete</button>
        </td>
    </tr>
</tbody>

This is what happen when those all executed : enter image description here

no array fetched by $scope at all. weird thing is the <tr> is repeated 5 time without any value. but when i call array[0] the $scope can fetch it :

<table class="table table-bordered pagin-table">
<thead>
    <tr>
        <th>No</th>
        <th>Title</th>
        <th>Description</th>
        <th width="220px">Action</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="x in items">
        <td>{{ $index + 1 }}</td>
        <td>{{ x[0].title }}</td>
        <td>{{ x[0].description }}</td>
        <td>
            <button data-toggle="modal" ng-click="edit(x.id)" data-target="#edit-data" class="btn btn-primary">Edit</button>
            <button ng-click="remove(x,$index)" class="btn btn-danger">Delete</button>
        </td>
    </tr>
</tbody>

enter image description here

Where did i go wrong?? can someone help me??


Solution

  • It is because the promise returning raw HTTP response from the server rather than parsed result data. You should try this instead :

    $http.get('Api/items').then(function(response)
            {       
                $scope.items = response.data;
                console.log(response);
            });