控制器在AngularJS中调用了两次

时间:2017-01-16 07:53:59

标签: angularjs angular-routing controllers

我在我的代码中使用了角度路由,以下是代码片段。 问题是主控制器被调用两次。我已经注意不要在标记中再次声明它(如所建议的那样)。我怀疑我的路由代码有问题。

    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>

控制器:

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

路由代码:

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

1 个答案:

答案 0 :(得分:2)

是的,因为

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

此代码与 $ routeChangeStart $ routeChangeSuccess 的路由更改事件相比,您的标记值因此 ng-if 也会被调用两次

  

纳克视

从ng-view指令中删除ng-if可以帮助你......

以我的方式:::你应该使用show和hide指令.... 像这样::

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