【问题标题】:How to redirect to another page using AngularJS?如何使用 AngularJS 重定向到另一个页面?
【发布时间】:2015-03-12 13:46:15
【问题描述】:

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

【问题讨论】:

  • 为什么需要使用 Angular 来实现?有什么具体原因吗? document.location 是正确的方式,可能比角度方式更有效

标签: javascript angularjs


【解决方案1】:

在 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】:

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

    或创建 scope $window

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

    【讨论】:

      【解决方案3】:

      我在 Angular 应用程序中也遇到了重定向到不同页面的问题

      您可以按照 Ewald 在他的回答中建议的那样添加 $window,或者如果您不想添加 $window,只需添加一个超时即可!

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

      【讨论】:

        【解决方案4】:

        如果你想使用链接那么:在html中有:

        <button type="button" id="btnOpenLine" class="btn btn-default btn-sm" ng-click="orderMaster.openLineItems()">Order Line Items</button>
        

        在打字稿文件中

        public openLineItems() {
        if (this.$stateParams.id == 0) {
            this.Flash.create('warning', "Need to save order!", 3000);
            return
        }
        this.$window.open('#/orderLineitems/' + this.$stateParams.id);
        

        }

        我希望您看到这个示例对我有帮助,因为它对我以及其他答案都有帮助。

        【讨论】:

          【解决方案5】:

          在您不必重新加载和引导整个应用程序配置的情况下,使用 $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
             }
          
          })();
          

          【讨论】:

            【解决方案6】:

            我使用的简单方法是

            app.controller("Back2Square1Controller", function($scope, $location) {
                window.location.assign(basePath + "/index.html");
            });
            

            【讨论】:

              【解决方案7】:
               (function () {
              "use strict";
              angular.module("myApp")
                     .controller("LoginCtrl", LoginCtrl);
              
              function LoginCtrl($scope, $log, loginSrv, notify) {
              
                  $scope.validateUser = function () {
                      loginSrv.validateLogin($scope.username, $scope.password)
                          .then(function (data) {
                              if (data.isValidUser) {
                                  window.location.href = '/index.html';
                              }
                              else {
                                  $log.error("error handler message");
                              }
                          })
                  }
              } }());
              

              【讨论】:

                【解决方案8】:

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

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

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

                【讨论】:

                  【解决方案9】:

                  $location.path('/configuration/streaming'); 这将工作...... 在控制器中注入定位服务

                  【讨论】:

                    【解决方案10】:

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

                    【讨论】:

                    • 我使用了 $window.location.href 但它给出了未定义函数 $window.location 的错误。我需要为此添加任何依赖项吗?
                    • 否,但您可能需要将 $window 注入控制器。请参阅我编辑的答案。
                    • 它的 window.location.href 不是 $window.location.href
                    • @user3623224 - 实际上不是 ;)
                    • @Junaid window.location.href 用于传统窗口对象,$window.location.href 用于AngularJS $window 对象,此处:docs.angularjs.org/api/ng/service/$window
                    【解决方案11】:

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

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

                    我建议您阅读$location$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");
                        };
                      }
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2011-02-22
                        • 2011-06-19
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多