$viewContentLoaded 在 Angular ngRoute 应用程序中被多次触发

$viewContentLoaded gets triggered multiple times in Angular ngRoute application

我非常直接地设置了两个选项卡,主页和管理员:

  $routeProvider
             // route for the home page
             .when('/home', {
             templateUrl : 'views/home.html',
             controller  : 'myCtrl',
             controllerAs: 'vm',
             resolve:{
                 loadDropDowns:function(DataSvc,$rootScope){
                    
                        return DataSvc.GetDropDowns();
                    
                 }
             }
         })
         // route for admin page
         .when('/admin',{
             templateUrl : 'admin/templates/admin.html'             
         })

并且在控制器中,我有一个 $viewContentLoaded 事件的侦听器 像这样:

$rootScope.$on('$viewContentLoaded', function(event){
        console.log(" viewContentLoaded fired ");
      });

每次我单击主页选项卡时,事件处理程序都会触发两次,所以第一次是 2 ,然后是 4 ,然后是 8 等等...

我在加载下拉列表时广播了另一个事件,对于一个广播事件,我也多次触发处理程序。

 $rootScope.$broadcast('dropDownsSet');

并且在同一个控制器中:

    $rootScope.$on('dropDownsSet', function(event, mass) {}

也执行了多次..(同上,每次加倍触发事件处理程序的次数)

我束手无策,这疯狂的原因可能是什么?

移动事件绑定代码

$rootScope.$on('$viewContentLoaded', function(event){
  console.log(" viewContentLoaded fired ");
});

myCtrl 控制器到某个主应用程序(父)控制器。现在发生的情况是,每次您导航到“主页”选项卡时,myCtrl 都会被实例化,从而在 $rootScope.

上再注册一个事件侦听器
$rootScope.$on('dropDownsSet', function(event, mass) {}

$rootScope 侦听器事件不会被破坏。您需要使用 $destroy 销毁它。最好使用 $scope.$on,因为 $scope 上的监听器会自动销毁。

$scope.$on('dropDownsSet', function(event, mass) {}

或者,

  var customeEventListener = $rootScope.$on('dropDownsSet', function(event, mass) {

    }

 $scope.$on('$destroy', function() {
        customeEventListener();
    });