Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make controller in angular main layout run on route change?

Tags:

angularjs

I have an angular page that has an ng-controller directive and an ng-view directive.

<body ng-controller="MainController">
   <h1>Welcome to my main template</h1
   <ng-view></ng-view>
</body>

I also have routes configured.

angular.module('app', []).
    config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
        $routeProvider.
            when('/', {templateUrl: '/templates/home.html', controller: HomeController}).
            when('/start', {templateUrl: '/templates/start.html', controller: StartController});

        $locationProvider.html5Mode(true);
}]);

When I click a URL that routes me to /start for example, only StartController runs, not MainController. I guess this kind of makes sense since the main layout has already loaded, and then the template only needs to be loaded now, but there is logic in my MainController that controls part of the template view I need to run.

However, if I refresh the entire page, both controllers run.

Is there any way to make both controllers run? Is this the wrong pattern to follow?

like image 523
robr Avatar asked Feb 15 '23 02:02

robr


1 Answers

Listen for $routeChangeSuccess on your main controller to get notified when route changes.

app.controller('MainController', function($scope) {
  $scope.$on('$routeChangeSuccess', function(event, current, previous, rejection) {
    if (current == 'someRoute') {
      //execute some route logic
    }
  });

})
like image 92
package Avatar answered May 05 '23 04:05

package