I'm building a basic AngularJS Login page and the $window.location.href did not re-direct the page to a new html in my system, hosted by WAMP. I even tried re-directing it to google. Nothing happens. I tried all the available solutions here and nothing seems to work. Any solutions ?
JS followed by HTML
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.submit = function() {
if ($scope.username && $scope.password) {
var user = $scope.username;
var pass = $scope.password;
if (pass == "admin" && user == "admin@admin.com") {
alert("Login Successful");
$window.location.href = "http://google.com"; //Re-direction to some page
} else if (user != "admin@admin.com") {
alert("Invalid username");
} else if (pass != "admin" && user == "admin@admin.com") {
alert("Invalid password");
}
} else {
alert("Invalid Login");
}
}
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="login.js"></script>
<link rel="stylesheet" href="login.css">
</head>
<body ng-controller="MainCtrl">
<form>
<label>Username:</label>
<input type="email" ng-model="username" class="lab1" />
</br>
</br>
<label></label>Password:</label>
<input type="password" ng-model="password" class="lab2">
</br>
<button type="submit" ng-click="submit()" class="buttonclass">login</button>
</form>
</body>
</html>
It is worth noting the current documentation for
$location
. Specifically the quote:If you need to redirect the browser to a new page, $window.location is definitely recommended.
You can use
$window.location.href
in AngularJSIn angular js you can use
$location
. Inject it in your controller :And if you want to redirect to google use its
url()
method :you can also use
path()
method for relative url :https://docs.angularjs.org/api/ng/service/$location
My two cents -
I could not get
$window.location.href
or$location.path
to work to navigate away from a page. In the documentation for$location
(under caveats) it says:$location Caveats
Documentation for $window is... lacking. Regardless, neither of the services worked for me in the controller (though $location.path works in my
index.run
file).In this project I am using ui-router, so doing this worked:
$state.go('state.name');
-- where state.name is the string of the state/page name to which the user wants to go, i.e.'index.users'
Angular has its own location handler named
$location
which I prefer to use in angular app;inject to your controller and use as following;