angularjs ng-if not empty for ng-repeat

guilhebl picture guilhebl · Aug 26, 2014 · Viewed 10k times · Source

I have a list of elements I want to display only if not null and empty, and for that I placed a ng-if before a ng-repeat block:

            <tbody ng-if="adsNotEmpty">

                <!-- Start: list_row -->
                <tr ng-repeat="ad in ads">
                    <td>{{$index + 1}}</td>
                    <ad-thumbnail ad="ad"/>
                </tr>                   
                <!-- End: list_row -->

            </tbody>

for that I have a controller code which evaluates the ads list and sets the adsNotEmpty var:

controllers.controller('AdCtrl', ['$scope', 'AdService',
  function($scope, AdService) {
    $scope.ads = AdService.query();
    $scope.adsNotEmpty = ($scope.ads && $scope.ads.length > 0);
  }]);

I have a RESTful webservice which currently returns HTTP 200 OK status with an empty response, even though the adsNotEmpty results to false the code enters inside of ad-thumbnail directive:

ad-thumbnail directive content:

<td>
AD - {{ad.name}}
</td>

the resulting HTML ends up printing AD - on the screen even though the ads list is empty.

the resulting object from

$scope.ads = AdService.query();

shows on debug:

Array[0]
$promise: Object
$resolved: false
length: 0
__proto__: Array[0]

What could be wrong with the code above to prevent angular from rendering the ad-thumbnail directive ?

I am posting the solution here for reference:

in controller:

controllers.controller('AdCtrl', ['$scope', 'AdService',
  function($scope, AdService) {

    AdService.query(function(data) {
        $scope.ads = data;
        $scope.adsNotEmpty = ($scope.ads.length > 0);
    });

and in page:

    <tbody>
        <!-- Start: list_row -->
        <tr ng-repeat="ad in ads">
            <td ng-if="adsNotEmpty">{{$index + 1}}</td>
            <ad-thumbnail ad="ad" ng-if="adsNotEmpty"/>
        </tr>                   
        <!-- End: list_row -->
    </tbody>

Answer

PSL picture PSL · Aug 26, 2014

The log shows you that you are not looking at what you should. You need to chain through the $promise returned by the Query, before looking for data.

   AdService.query().$promise.then(function(data) {
       $scope.ads = data;
       $scope.adsNotEmpty = ($scope.ads && $scope.ads.length);
   });

ng-repeat at tha instance is iterating through the properties of the object returned by Query hance you see blank AD-