Naterade
Naterade

Reputation: 2675

ng-show works but shows both divs quickly

So, using an Angular.js controller I grab a result set from the database, the data is irrelevant. When the result comes back false (no rows found) the correct div shows "empty!".

When the result comes back true, the div "empty!" shows for a split second and then "results!" shows. The behavior reminds me of jQuery .hide(), I put my code below, but I still can't figure out why this behavior is happening?

HTML:

<h1 class="page-header">
    Products 
    <small>
        <i class="fa fa-angle-double-right text-primary"></i> add
    </small>
</h1>

<div class="row">
    <div class="col-sm-12 col-md-12 col-lg-12">
        <div ng-show="categoriesFound">results!</div>
        <div ng-show="!categoriesFound">empty!</div>
    </div>
</div>

Angular controller:

mbpApp.controller('ProductsCtrl', function(httpService, $scope) {
    httpService.productCategoriesFindAll().then(function(d) {
    $scope.data = d;

        if(d.status) {
            $scope.categoriesFound = true;
        } else {
            $scope.categoriesFound = false;
        }
  });
});

Upvotes: 0

Views: 691

Answers (1)

Zoey Mertes
Zoey Mertes

Reputation: 3144

That's because before you set $scope.categoriesFound, the template has to be processed. Angular expressions are forgiving of undefined but still report it as undefined, so the results! div's ng-show is false, and the empty! div's ng-show is !false, which is true.

You can resolve this by doing $scope.categoriesFound = true; at the beginning, but then that will show results! before you even get your response back.

Instead what you can do is add another variable (something like categoriesLoading), set that to true when you make the request, and add conditions in your templates to show some kind of loading indicator. When the request completes and is processed, set it to false and then populate the categoriesFound variable

Upvotes: 3

Related Questions