控制器在 AngularJS 中调用了两次
Controller called twice in AngularJS
我在我的代码中使用 angular-routing ,下面是代码片段。
问题是主控制器被调用了两次。我已经注意不要在标记中再次声明它(到处都是建议的)。我怀疑我的路由代码有问题。
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"
})
});
是的,因为
<div class="right_col" ng-if='!isRouteLoading' style="padding-top: 60px;" ng-view>
此代码与 $routeChangeStart 和 $routeChangeSuccess 的路线更改事件相同,您切换值 因此 ng-if 也被叫了两次
ng-view
从 ng-view 指令中删除 ng-if 可以帮助您...
以我的方式:::你应该使用显示和隐藏指令....
像这样::
<div class="right_col" ng-show='!isRouteLoading' style="padding-top: 60px;" ng-view>
我在我的代码中使用 angular-routing ,下面是代码片段。 问题是主控制器被调用了两次。我已经注意不要在标记中再次声明它(到处都是建议的)。我怀疑我的路由代码有问题。
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"
})
});
是的,因为
<div class="right_col" ng-if='!isRouteLoading' style="padding-top: 60px;" ng-view>
此代码与 $routeChangeStart 和 $routeChangeSuccess 的路线更改事件相同,您切换值 因此 ng-if 也被叫了两次
ng-view
从 ng-view 指令中删除 ng-if 可以帮助您...
以我的方式:::你应该使用显示和隐藏指令.... 像这样::
<div class="right_col" ng-show='!isRouteLoading' style="padding-top: 60px;" ng-view>