How to watch for a route change in AngularJS?
Note: This is a proper answer for a legacy version of AngularJS. See this question for updated versions.
$scope.$on('$routeChangeStart', function($event, next, current) {
// ... you could trigger something here ...
});
The following events are also available (their callback functions take different arguments):
- $routeChangeSuccess
- $routeChangeError
- $routeUpdate - if reloadOnSearch property has been set to false
See the $route docs.
There are two other undocumented events:
- $locationChangeStart
- $locationChangeSuccess
See What's the difference between $locationChangeSuccess and $locationChangeStart?
Detect route change in an Angular service
By using $routeChangeStart, you are listening to a broadcast sent by $routeProvider on every change of the route. I don't think you need to call it in multiple places ( controllers ), just to check this.
In your service:
angular.module('lmsApp')
.service('pageAuth', ['$location', function ($location) {
var canAccess = function(event,next,current){
var user = firebase.auth().currentUser;
//requireAuth is a custom route property
if (next.$$route.requireAuth && user == null ) {
event.preventDefault(); //prevents route change
alert("You must be logged in to access page!");
}
else {
console.log("allowed");
}
}
$rootScope.$on('$routeChangeStart',canAccess);
}]);
And then inject your service in the .run()
part of your application. This will ensure the check will be done automatically ( by the broadcast as mentioned earlier ).
In you config part :
angular.module('lmsApp')
.run(function runApp(pageAuth){
//rest of your stuff
});
AngularJS confirm before route change
Demo: http://plnkr.co/edit/Aq8uYg
In the demo, if you change the value of input, you will be noticed when trying to go back.
Listen to $locationChangeStart
and use event.preventDefault()
to cancel the location change if changes not confirmed.
This method has one advantage over $route.reload()
: current controller and models will not be re-instantiated. thus all of your variables are kept the same as user click the "Back" button.
How to detect route change in Angular 1.5 component router?
Sajeetharan s' answer is correct but its only for current scope.If you want it for every state change add it like this
run.$inject = ['$rootScope', '$location', '$cookieStore', '$http'];
function run($rootScope, $location, $cookieStore, $http) {
$rootScope.$on('$locationChangeStart', function(event, next, current) {
console.log($location.path());
});
}
app.run(run);
Route change events while trying to avoid using $rootScope
You missread that.
First of all, this event was added by Angular team - do you think they recommend not to use it?:D That article is about that you should not put everything to $rootScope, which seems to be an easy way for beginners.
Actually, using $rootScope
- for for global events is absolutely ok -- that is actual purpose of this service.
AngularJs - cancel route change event
Instead of $routeChangeStart
use $locationChangeStart
Here's the discussion about it from the angularjs guys: https://github.com/angular/angular.js/issues/2109
Edit 3/6/2018 You can find it in the docs: https://docs.angularjs.org/api/ng/service/$location#event-$locationChangeStart
Example:
$scope.$on('$locationChangeStart', function(event, next, current) {
if ($scope.form.$invalid) {
event.preventDefault();
}
});
AngularJS call scope function on route change
You can try this in your controller :
$scope.$on('$locationChangeStart', function(event) {
//your code here
});
Related Topics
How to Create a Dialog with "Ok" and "Cancel" Options
Jquery Selectors on Custom Data Attributes Using HTML5
Get First and Last Date of Current Month with JavaScript or Jquery
Making Custom Right-Click Context Menus for My Web-App
Moment Js Date Time Comparison
How to Find the Height of Text on an HTML Canvas
Adding Custom Functions into Array.Prototype
Onclick Not Working on Mobile (Touch)
React-Router: No Not Found Route
JavaScript Event Handler with Parameters
Casting Plain Objects to Class Instances in JavaScript
How to Access Local Scope Dynamically in JavaScript
How to Link Each User to Their Data in Firebase
When and Why to 'Return False' in JavaScript