1

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"
    })
  });
8
  • can you recreate the issue in a fiddle Commented Jan 16, 2017 at 7:56
  • Post a complete, minimal example reproducing the problem. Include all the necessary stuff, and exclude all the irrlevant stuff (like your routeLoadingIndicator). Commented Jan 16, 2017 at 7:59
  • 1
    The code is working fine. check this out jsfiddle.net/ebinmanuval/c8u34s37 Commented Jan 16, 2017 at 8:06
  • did you check this ? Commented Jan 16, 2017 at 8:06
  • why do you have an ng-if on same element as ng-view? Commented Jan 16, 2017 at 8:16

1 Answer 1

2

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>   
Sign up to request clarification or add additional context in comments.

1 Comment

For the sake of clarity, it works because using ng-show does not recreate the directive's elements, but hide/show them. When angular recreate the div element (using ng-if) your controller get called again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.