How to redirect to another page using AngularJS?
You can use Angular $window
:
$window.location.href = '/index.html';
Example usage in a contoller:
(function () {
'use strict';
angular
.module('app')
.controller('LoginCtrl', LoginCtrl);
LoginCtrl.$inject = ['$window', 'loginSrv', 'notify'];
function LoginCtrl($window, loginSrv, notify) {
/* jshint validthis:true */
var vm = this;
vm.validateUser = function () {
loginSrv.validateLogin(vm.username, vm.password).then(function (data) {
if (data.isValidUser) {
$window.location.href = '/index.html';
}
else
alert('Login incorrect');
});
}
}
})();
You can redirect to a new URL in different ways.
- You can use $window which will also refresh the page
- You can "stay inside" the single page app and use $location in which case you can choose between
$location.path(YOUR_URL);
or$location.url(YOUR_URL);
. So the basic difference between the 2 methods is that$location.url()
also affects get parameters whilst$location.path()
does not.
I would recommend reading the docs on $location
and $window
so you get a better grasp on the differences between them.
$location.path('/configuration/streaming');
this will work...
inject the location service in controller
I used the below code to redirect to new page
$window.location.href = '/foldername/page.html';
and injected $window object in my controller function.
It might help you!!
The AngularJs code-sample
var app = angular.module('app', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
// For any unmatched url, send to /index
$urlRouterProvider.otherwise("/login");
$stateProvider
.state('login', {
url: "/login",
templateUrl: "login.html",
controller: "LoginCheckController"
})
.state('SuccessPage', {
url: "/SuccessPage",
templateUrl: "SuccessPage.html",
//controller: "LoginCheckController"
});
});
app.controller('LoginCheckController', ['$scope', '$location', LoginCheckController]);
function LoginCheckController($scope, $location) {
$scope.users = [{
UserName: 'chandra',
Password: 'hello'
}, {
UserName: 'Harish',
Password: 'hi'
}, {
UserName: 'Chinthu',
Password: 'hi'
}];
$scope.LoginCheck = function() {
$location.path("SuccessPage");
};
$scope.go = function(path) {
$location.path("/SuccessPage");
};
}