如何使用AngularJS重定向到另一个页面?

2022-08-30 02:03:20

我正在使用ajax调用在服务文件中执行功能,如果响应成功,我想将页面重定向到另一个URL。目前,我正在通过普通的JS代码来执行此操作。但是我需要用AngularJS代码替换它。我已经在stackoverflow上寻找了各种解决方案,他们使用了.但我是AngularJS的新手,并且在实现它时遇到了麻烦。window.location = response['message'];$location

$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
        })

答案 1

您可以使用 Angular :$window

$window.location.href = '/index.html';

在 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');
            });
        }
    }
})();

答案 2

您可以通过不同的方式重定向到新的 URL。

  1. 您可以使用$window,这也将刷新页面
  2. 您可以“留在”单页应用程序并使用$location在这种情况下,您可以在 或 之间进行选择。因此,这两种方法之间的基本区别在于,这也会影响获取参数,而实际上则不然。$location.path(YOUR_URL);$location.url(YOUR_URL);$location.url()$location.path()

我建议您继续阅读文档,以便您更好地了解它们之间的差异。$location$window