user3685285
user3685285

Reputation: 6586

angular ng-if keeps refreshing page

I have the following divs setup where I switch between a loading div and an angular view. Only the loading div should show up when globalCtx.viewportLoading == true, and only the ng-view should show up when globalCtx.viewportLoading == false:

<div id="viewContainer">
    <div class="loader" ng-if="globalCtx.viewportLoading"></div>
    <div ng-view ng-if="!globalCtx.viewportLoading"></div>
</div>

The variable globalCtx is defined in an angular service like so:

app.factory("globalCtx", function () {
    var service = {
        viewportLoading: false
    };
    return service;
});

On every route, I have a different view and a different angular controller. For each of these views, I show the loading div until the page loads like so:

Generate Request

var req = {
    method: 'POST',
    url: 'api/v1/work/do-something',
    data: request,
    headers: {
        'Content-Type': "application/json; charset=utf-8"
    }
}

Set Loading to True

globalCtx.viewportLoading = true

Make Request, and set viewportLoading to false on reply

$http(req).then(function (resp) {

    // ... do something ...

    globalCtx.viewportLoading = false
},
function (resp) {
    alert('Error fetching data from server!');
});

This works for the first page I run on. Say, the home page. But any page I route to after that, it just keeps refreshing that page. Say, I Go to the home page. It makes one request for data. I then route to page1, and I notice the angular controller for page1 keeps refreshing and is being created over and over again. Why is this? Does it have to do with ng-if?

Upvotes: 0

Views: 1329

Answers (1)

Murari Pradip Singh
Murari Pradip Singh

Reputation: 39

Please use this code for loading your view

 globalCtx.viewportLoading = false;
 $scope.$on('$viewContentLoaded', function(){
  globalCtx.viewportLoading = true;
 });

Upvotes: -2

Related Questions