小编典典

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

angularjs

我正在使用ajax调用在服务文件中执行功能,并且如果响应成功,我想将页面重定向到另一个URL。目前,我正在通过使用简单的js“
window.location = response[‘message’];”来做到这一点。但是我需要用angularjs代码替换它。我看过关于的各种解决方案,他们使用了$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
        })

阅读 393

收藏
2020-07-04

共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');
            });
        }
    }
})();
2020-07-04