Redirect to new Page in AngularJS using $location
AngularjsRedirectAngularjs Problem Overview
I am testing with the following AngularJS $location. I don't what's the problem with this. Just want to check if the redirection is working or not:
HTML
<body data-ng-controller="MainCtrl">
Hello {{name}}!
<button ng-click='go()'>Go</button>
</body>
AngularJS code
var app = angular.module('location', []);
app.controller('MainCtrl', function($scope,$routeParams, $location) {
$scope.name = 'World';
$scope.go = function() {
$location.absUrl() = 'http://www.google.com';
}
});
Angularjs Solutions
Solution 1 - Angularjs
$location won't help you with external URLs, use the $window service instead:
$window.location.href = 'http://www.google.com';
Note that you could use the window object, but it is bad practice since $window is easily mockable whereas window is not.
Solution 2 - Angularjs
If you want to change ng-view you'll have to use the '#'
$window.location.href= "#operation";
Solution 3 - Angularjs
The line
$location.absUrl() == 'http://www.google.com';
is wrong. First == makes a comparison, and what you are probably trying to do is an assignment, which is with simple = and not double ==.
And because absUrl() getter only. You can use url(), which can be used as a setter or as a getter if you want.
reference : http://docs.angularjs.org/api/ng.$location
Solution 4 - Angularjs
It might help you!
AngularJs Code-sample
var app = angular.module('urlApp', []);
app.controller('urlCtrl', function ($scope, $log, $window) {
$scope.ClickMeToRedirect = function () {
var url = "http://" + $window.location.host + "/Account/Login";
$log.log(url);
$window.location.href = url;
};
});
HTML Code-sample
<div ng-app="urlApp">
<div ng-controller="urlCtrl">
Redirect to <a href="#" ng-click="ClickMeToRedirect()">Click Me!</a>
</div>
</div>
Solution 5 - Angularjs
this worked for me inside a directive and works without refreshing the baseurl (just adds the endpoint).Good for Single Page Apps with routing mechanism.
$(location).attr('href', 'http://localhost:10005/#/endpoint')
Solution 6 - Angularjs
Try entering the url inside the function
$location.url('http://www.google.com')