小编典典

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

all

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

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

阅读 1329

收藏
2022-09-02

共1个答案

小编典典

您可以使用 Angular $window

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

控制器中的示例用法:

(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');
            });
        }
    }
})();
2022-09-02