Reputation: 869
I have an app built on angular.js, and I want to run a function whenever the route is changed and a new template is rendered in the view. I found a way to do it in a controller when it is activated, like this:
$scope.$on('$routeChangeStart', function(next, current){
//...do stuff here...
});
But is there a way to run a function on each route change, so I only have to enter it once?
Upvotes: 0
Views: 1721
Reputation: 107
I have a better solution. U can add a run block in your main file (where u define your app) and insert an event handeer for $routeChangeStart. This way u dont have to add anything to your html. see my exmaple:
yourAppNAme.run(function($rootScope) {
$scope.$on('$routeChangeStart', function(next, current){
//...do stuff here...
});
});
this exmaple cheked and i currently working on my angularjs app.
Upvotes: 3
Reputation: 42669
If this is your view
<div ng-app='myApp'>
<ng-view/>
</div>
change it to
<div ng-app='myApp' ng-controller='RootController'>
<ng-view/>
</div>
In your RootController
you can add the event handler for $routeChangeStart
. Since your RootController
is created once and remains for the lifetime of the app you can safely subscribe to this event here.
Upvotes: 1