nam vo
nam vo

Reputation: 3457

angularjs ng-if loads earlier than the controller

I have a view that take data from a controller.

app.controller('teamLoadCtrl', ['$scope', '$rootScope', 'dataService', function ($scope, $rootScope, dataService) {

    $scope.$watch(function () {
        return $rootScope.categoryId;   << wait till this has value
    }, function (newValue) {
        dataService.getteamsbyleague($rootScope.categoryId).then(function (data) {
            $scope.teams = data;            
        });
    });

}]);

On View:

<section class="team-club" ng-controller="teamLoadCtrl" ng-if="teams.length>0"> 
    {{teamCount  }}  >> show correct number (20)
    <ul>
        <li ng-repeat="item in teams">
           ...
        </li>
    </ul>
    <div class="clearfix"></div>
</section>

I guess the problem is ng-if executes before the controller got the data. It works fine without ng-if.

Anyway to fix it ? Thanks all.

Upvotes: 0

Views: 242

Answers (2)

A.B
A.B

Reputation: 20455

use ng-cloak on that div and use this css

[ng\:cloak], [ng-cloak], .ng-cloak {
        display: none !important;
    }

Alternatively you can use resolve property on the state for example

example

.state('yourroute', {
    url: "",
    templateUrl: 'partials/yourroute.html',
    controller:'teamLoadCtrl',
    abstract:true, 
    resolve : {
        result_data: function ($q)
        {

             var deferred = $q.defer();    
       dataService.getteamsbyleague($rootScope.categoryId).success(function(data) {
           deferred.resolve(data);
        });
           return deferred.promise;
        } 
    }
})

In controller

app.controller('teamLoadCtrl', ['$scope','result_data', '$rootScope', 'dataService', function ($scope,result_data, $rootScope, dataService) {

 $scope.teams = result_data;
}]);

Upvotes: 1

Sly_cardinal
Sly_cardinal

Reputation: 13043

For you case changing the ng-if to ng-show will fix things.

<section class="team-club" ng-controller="teamLoadCtrl" ng-show="teams.length>0"> 
    {{teamCount  }}  >> show correct number (20)
    <ul>
        <li ng-repeat="item in teams">
           ...
        </li>
    </ul>
    <div class="clearfix"></div>
</section>

There won't really be any performance difference because the ng-repeat will remove all the items if the team length is zero anyway.

Upvotes: 0

Related Questions