AngularJS ng-repeat does not return data, returns always empty

1

I have a query to an API that theoretically is returning the data, at least in the console shows me the same. But in View with ng-repeat is not bringing anything.

Below is the code I'm using:

Factory:

pcFactories.factory('TeacherSrv', function ($http) {
    return {
        getAllTeachers: function (TTBId) {
            $http.get('http://xxx.xxx.xxx/' + TTBId)
                .success(function (data) {
                    return data;
                })
                .error(function (status) {
                    return status;
              });
        }
    };
})

Controller

   pcControllers.controller('TeacherCtrl', function ($scope, TeacherSrv) {
        $scope.teachers = TeacherSrv.getAllTeachers(TTBId);
    })

View

<tr ng-repeat="t in teachers" on-finish-render="ngRepeatFinished">
   <td>
     <img src="Images/no-photo.png" alt="" />
     <a href="" class="user-link">{{t.TEAName}}</a>
     <span class="user-subhead">{{t.TEAEmail}}</span>
   </td>
</tr>

I hope you can help me.

    
asked by anonymous 07.04.2015 / 19:15

2 answers

1

The problem is not in Angular, but in the way you manipulate the results returned by the API call.

The return data; line is returning data within the function executed by promise , not factory .

Changing the getAllTeachers method to return a promise , and manipulating promise within your controller solves the problem.

pcFactories.factory('TeacherSrv', function ($http) {
    return {
        getAllTeachers: function (TTBId) {
            return $http.get('http://xxx.xxx.xxx/' + TTBId);
        }
    };
});

pcControllers.controller('TeacherCtrl', function ($scope, TeacherSrv) {
    $scope.teachers = null;
    TeacherSrv.getAllTeachers(TTBId).success(function (data) {
        $scope.teachers = data;
    })
    .error(function (status) {
        $scope.teachers = status;
    });
});

All this is due to the asynchronous behavior of Javascript, and to the fact that you are not returning anything in the getAllTeachers method.

Note: You do not have to specify http:// in the URL in method get service $http .

    
07.04.2015 / 19:26
1

I believe what is happening is that when ng-repeat runs the API data has not yet been returned. That way teachers is still empty and ng-repeat will not show anything.

One way to solve this problem is as follows:

pcControllers.controller('TeacherCtrl', function ($scope, TeacherSrv) {
    TeacherSrv.getAllTeachers(TTBId).then(function(result){
       $scope.teachers = result.data;
    });
})

What I've changed above was the following:

  • TeacherSrv.getAllTeachers (TTBId) returns a $ promise , which when finished will update the value of $ scope.teachers. This way you ensures that your ng-repeat will perform as expected as soon as the API data is returned.
07.04.2015 / 19:26