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?
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
}
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With