Javascript 如何使用 AngularJS 重定向到另一个页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27941876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to redirect to another page using AngularJS?
提问by Farjad Hasan
I am using ajax call to perform functionality in a service file and if the response is successful, I want to redirect the page to another url. Currently, I am doing this by using simple js "window.location = response['message'];". But I need to replace it with angularjs code. I have looked various solutions on stackoverflow, they used $location. But I am new to angular and having trouble to implement it.
我正在使用 ajax 调用在服务文件中执行功能,如果响应成功,我想将页面重定向到另一个 url。目前,我通过使用简单的 js“window.location = response['message'];”来做到这一点。但我需要用 angularjs 代码替换它。我在stackoverflow上查看了各种解决方案,他们使用了$location。但我是 angular 的新手并且难以实现它。
$http({
url: RootURL+'app-code/common.service.php',
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
dataType: 'json',
data:data + '&method=signin'
}).success(function (response) {
console.log(response);
if (response['code'] == '420') {
$scope.message = response['message'];
$scope.loginPassword = '';
}
else if (response['code'] != '200'){
$scope.message = response['message'];
$scope.loginPassword = '';
}
else {
window.location = response['message'];
}
// $scope.users = data.users; // assign $scope.persons here as promise is resolved here
})
回答by Ewald Stieger
You can use Angular $window:
您可以使用 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');
});
}
}
})();
回答by Cristi Berceanu
You can redirect to a new URL in different ways.
您可以通过不同方式重定向到新 URL。
- You can use $windowwhich will also refresh the page
- You can "stay inside" the single page app and use $locationin 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.
- 您可以使用$window这也将刷新页面
- 您可以“留在”单页应用程序中并使用$location在这种情况下,您可以在
$location.path(YOUR_URL);或之间进行选择$location.url(YOUR_URL);。所以这两种方法之间的基本区别是$location.url()也会影响获取参数,而$location.path()不会。
I would recommend reading the docs on $locationand $windowso you get a better grasp on the differences between them.
我建议阅读文档$location,$window以便更好地了解它们之间的差异。
回答by user2266928
$location.path('/configuration/streaming');this will work...
inject the location service in controller
$location.path('/configuration/streaming');这将工作......在控制器中注入位置服务
回答by Sanchi Girotra
I used the below code to redirect to new page
我使用以下代码重定向到新页面
$window.location.href = '/foldername/page.html';
and injected $window object in my controller function.
并在我的控制器函数中注入了 $window 对象。
回答by Anil Singh
It might help you!!
或许能帮到你!!
The AngularJs code-sample
AngularJs 代码示例
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");
};
}
回答by Rizo
In AngularJS you can redirect your form(on submit) to other page by using window.location.href='';like below:
在 AngularJS 中,您可以使用如下方式将您的表单(提交时)重定向到其他页面window.location.href='';:
postData(email){
if (email=='undefined') {
this.Utils.showToast('Invalid Email');
} else {
var origin = 'Dubai';
this.download.postEmail(email, origin).then(data => {
...
});
window.location.href = "https://www.thesoftdesign.com/";
}
}
Simply try this:
简单地试试这个:
window.location.href = "https://www.thesoftdesign.com/";
回答by Vignesh Subramanian
I faced issues in redirecting to a different page in an angular app as well
我在 Angular 应用程序中重定向到不同页面时也遇到了问题
You can add the $windowas Ewald has suggested in his answer, or if you don't want to add the $window, just add an timeout and it will work!
您可以添加$windowEwald 在他的回答中建议的,或者如果您不想添加$window,只需添加超时即可!
setTimeout(function () {
window.location.href = "http://whereeveryouwant.com";
}, 500);
回答by raghavsood33
The simple way I use is
我使用的简单方法是
app.controller("Back2Square1Controller", function($scope, $location) {
window.location.assign(basePath + "/index.html");
});
回答by gsalgadotoledo
A good way to do this is using $state.go('statename', {params...}) is faster and more friendly for user experience in cases when you don't have to reload and bootsraping whole app config and stuff
一个很好的方法是使用 $state.go('statename', {params...}) 在您不必重新加载和引导整个应用程序配置和内容的情况下对用户体验更快、更友好
(function() {
'use strict';
angular
.module('app.appcode')
.controller('YourController', YourController);
YourController.$inject = ['rootURL', '$scope', '$state', '$http'];
function YourController(rootURL, $scope, $state, $http) {
$http({
url: rootURL + 'app-code/common.service.php',
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
dataType: 'json',
data:data + '&method=signin'
}).success(function (response) {
if (response['code'] == '420') {
$scope.message = response['message'];
$scope.loginPassword = '';
} else if (response['code'] != '200') {
$scope.message = response['message'];
$scope.loginPassword = '';
} else {
// $state.go('home'); // select here the route that you want to redirect
$state.go(response['state']); // response['state'] should be a route on your app.routes
}
})
}
});
// routes
// 路线
(function() {
'use strict';
angular
.module('app')
.config(routes);
routes.$inject = [
'$stateProvider',
'$urlRouterProvider'
];
function routes($stateProvider, $urlRouterProvider) {
/**
* Default path for any unmatched url
*/
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: '/app/home/home.html',
controller: 'Home'
})
.state('login', {
url: '/login',
templateUrl: '/app/login/login.html',
controller: 'YourController'
})
// ... more routes .state
}
})();
回答by Nour Lababidi
If you want to use a link then: in the html have:
如果要使用链接,则:在 html 中有:
<button type="button" id="btnOpenLine" class="btn btn-default btn-sm" ng-click="orderMaster.openLineItems()">Order Line Items</button>
in the typescript file
在打字稿文件中
public openLineItems() {
if (this.$stateParams.id == 0) {
this.Flash.create('warning', "Need to save order!", 3000);
return
}
this.$window.open('#/orderLineitems/' + this.$stateParams.id);
}
}
I hope you see this example helpful as it was for me along with the other answers.
我希望你看到这个例子有帮助,因为它对我以及其他答案都有帮助。

