Search code examples
angularjsangular-routingcontrollers

Controller called twice in AngularJS


I am using angular-routing in my code , for which following is the code Snippet. Problem is that the main controller is being called twice. I have already taken care of not declaring it again in markup ( as advised everywhere). I suspect there's something wrong in my routing code.

    app.directive('routeLoadingIndicator', function ($rootScope,$timeout) {
return {
    restrict:'E',
    link:function(scope, elem, attrs){
        scope.isRouteLoading = false;

        $rootScope.$on('$routeChangeStart', function(){
            scope.isRouteLoading = true;
        });
        $rootScope.$on('$routeChangeSuccess', function(){
            $timeout(function(){
                scope.isRouteLoading = false;                    
            }, 10);
        });
    }
};
});

HTML :

     <route-loading-indicator >
        <div  class="spinner" ng-if='isRouteLoading'>
            <div class="rectLoader"></div>                
        </div>
    <div class="right_col"  ng-if='!isRouteLoading' style="padding-top: 60px;"   ng-view>   
    </div>  </route-loading-indicator>

Controller :

   app.controller('main',   function($scope,$routeParams,$rootScope){
    console.log("main Controller");
  });

Routing Code :

   app.config(function($routeProvider) {
$routeProvider
    .when("/", {
        templateUrl : "xyz.html",
        controller : "main"
    })
  });

Solution

  • Yes right because of

    <div class="right_col"  ng-if='!isRouteLoading' style="padding-top: 60px;"   ng-view>   
    

    this code as on route change event of $routeChangeStart and $routeChangeSuccess you togging value Hence ng-if get called twice as well your

    ng-view

    Remove ng-if from ng-view directive can help you...

    In my way::: you should go with show and hide directive.... Like this::

    <div class="right_col"  ng-show='!isRouteLoading' style="padding-top: 60px;"   ng-view>