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

Published

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/

Source: AngularJS Questions

Published
Categorized as angularjs, javascript Tagged ,

Answers

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/')
   }
})

Duane Grimes

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq