簡體   English   中英

如何使用 AngularJS 重定向到另一個頁面?

[英]How to redirect to another page using AngularJS?

我正在使用 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 $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');
            });
        }
    }
})();

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

  1. 您可以使用$window這也將刷新頁面
  2. 您可以“留在”單頁應用程序中並使用$location在這種情況下,您可以在$location.path(YOUR_URL);之間進行選擇$location.path(YOUR_URL); $location.url(YOUR_URL); . 所以這兩種方法的基本區別是$location.url()也會影響 get 參數,而$location.path()不會。

我建議您閱讀有關$location$window的文檔,以便更好地了解它們之間的差異。

$location.path('/configuration/streaming'); 這將工作......在控制器中注入位置服務

我使用以下代碼重定向到新頁面

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

並在我的控制器函數中注入了 $window 對象。

或許能幫到你!!

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

在 AngularJS 中,您可以使用window.location.href='';將您的表單(提交時)重定向到其他頁面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/"; 

我在 Angular 應用程序中重定向到不同頁面時也遇到了問題

您可以按照 Ewald 在他的回答中的建議添加$window ,或者如果您不想添加$window ,只需添加超時即可!

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

我使用的簡單方法是

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

這樣做的一個好方法是使用 $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
   }

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

如果要使用鏈接,則:在 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);

}

我希望你看到這個例子有幫助,因為它對我以及其他答案都有幫助。

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

或創建scope $window

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM