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

175

我正在使用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
        })

2
你为什么需要使用Angular呢?有具体的原因吗?document.location是正确的方式,可能比Angular的方式更有效率。 - casraf
12个回答

236

你可以使用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');
            });
        }
    }
})();

1
我已经使用了 $window.location.href,但是它给出了一个未定义函数 $window.location 的错误。我需要包含任何依赖项吗? - Farjad Hasan
3
不需要,但你可能需要在你的控制器中注入$window。请参考我的编辑答案。 - Ewald Stieger
2
它是window.location.href而不是$window.location.href。 - Junaid
3
@user3623224 - 其实不是这样的 ;) - Ben
12
@Junaid:window.location.href 是针对传统窗口对象的,$window.location.href 是针对 AngularJS $window 对象的,文档链接在这里:https://docs.angularjs.org/api/ng/service/$window - Mikel Bitson

123

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

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

我建议阅读$location$window的文档,以便更好地掌握它们之间的区别。


16

$location.path('/configuration/streaming'); 这段代码将起作用... 在控制器中注入位置服务。


13

我使用以下代码将页面重定向到新页面

$window.location.href = '/foldername/page.html';

并且在我的控制器函数中注入了 $window 对象。


12

可能会对你有所帮助!!

这是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");
  };
}

5

我在一个angular app中重定向到另一个页面时遇到了问题。

你可以像Ewald在他的回答中建议的那样添加$window,或者如果你不想添加$window,只需添加一个timeout即可解决问题!

setTimeout(function () {
        window.location.href = "http://whereeveryouwant.com";
    }, 500);

5
在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/";      
    }
  }

只需尝试以下操作:
window.location.href = "https://www.thesoftdesign.com/"; 

2

一个好的方法是使用 $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
                }
            })
    }

});

// 路由

(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
   }

})();

2
我使用的简单方法是:
app.controller("Back2Square1Controller", function($scope, $location) {
    window.location.assign(basePath + "/index.html");
});

1

使用location.href="./index.html"

或创建$window范围

并使用$window.location.href="./index.html"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接