简体   繁体   中英

how to execute ng-init in angularJS everytime the route changes

I have index file

  <div ng-app="myApp"  data-ng-init="init()">
           
         <ng-view></ng-view>
           
    </div>

script looks like this

 var app = angular.module('myApp',  ['ngRoute'])
    
        app.config(function ($routeProvider, $locationProvider)
         {  
            $locationProvider.html5Mode(true);
            $routeProvider
            .when('/home/', 
               {  
                  template: 'home.html',
                  controller: 'homeController' 
              }) .
            when('/menu/', 
           {  
                templateUrl: 'menu.html',  
                controller: 'menuController'  
            })

   app.controller('homeController',function($scope,$rootScope){
     $scope.init=function(){
         alert('executing the init function')
         }
       })
   app.controller('menuController',function($scope,$location){
       if($scope.var1){
       $location.path('/home/')
       }
    })

the first time the path is /home/ the alert is triggered.but from the menu controller when the variable var1 is true then path is changed to /home/ again but the init function is not running and alert is not triggered. how can this be fixed. i want the init in homecontroller to run everytime the path is changed to /home/

You can try this. It might work.

var app = angular.module('myApp',  ['ngRoute'])

    app.config(function ($routeProvider, $locationProvider)
     {  
        $locationProvider.html5Mode(true);
        $routeProvider
        .when('/home/', 
           {  
              template: 'home.html',
              controller: 'homeController' 
          }) .
        when('/menu/', 
       {  
            templateUrl: 'menu.html',  
            controller: 'menuController'  
        })

app.controller('homeController',function($scope,$rootScope){
 var init=function(){
     alert('executing the init function')
     };
     
     init();
     
   })
app.controller('menuController',function($scope,$location){
   if($scope.var1){
   $location.path('/home/')
   }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM