จะเปลี่ยนเส้นทางไปยังหน้าอื่นโดยใช้ AngularJS ได้อย่างไร


171

ฉันใช้การโทร ajax เพื่อใช้งานฟังก์ชันในไฟล์บริการและหากการตอบสนองสำเร็จฉันต้องการเปลี่ยนเส้นทางหน้าเว็บไปยัง URL อื่น ขณะนี้ฉันกำลังทำสิ่งนี้โดยใช้ js แบบง่าย "window.location = response ['message'];" แต่ฉันต้องแทนที่ด้วยรหัส angularjs ฉันได้ดูวิธีแก้ปัญหาต่างๆใน stackoverflow พวกเขาใช้ตำแหน่ง $ แต่ฉันใหม่สำหรับเชิงมุมและมีปัญหาในการใช้งาน

$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
ทำไมคุณต้องใช้เชิงมุมสำหรับสิ่งนั้น มีเหตุผลเฉพาะเจาะจงหรือไม่ document.location เป็นวิธีที่เหมาะสมและอาจมีประสิทธิภาพมากกว่าแบบเชิงมุม
casraf

คำตอบ:


229

คุณสามารถใช้ 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 - ไม่จริง;)
เบ็

12
@Junaid window.location.href สำหรับวัตถุหน้าต่างแบบดั้งเดิม $ window.location.href สำหรับวัตถุหน้าต่าง AngularJS $ ที่นี่: docs.angularjs.org/api/ng/serv//$window
Mikel Bitson

122

คุณสามารถเปลี่ยนเส้นทางไปยัง URL ใหม่ได้หลายวิธี

  1. คุณสามารถใช้$ windowซึ่งจะรีเฟรชหน้า
  2. คุณสามารถ "อยู่ภายใน" แอปหน้าเดียวและการใช้$ ที่ตั้งซึ่งในกรณีนี้คุณสามารถเลือกระหว่างหรือ$location.path(YOUR_URL); $location.url(YOUR_URL);ดังนั้นความแตกต่างพื้นฐานระหว่าง 2 เมธอดก็คือมัน$location.url()ยังส่งผลต่อการรับพารามิเตอร์ในขณะที่$location.path()ไม่ได้

ฉันขอแนะนำให้อ่านเอกสาร$locationและ$windowคุณจะได้รับความเข้าใจที่ดีขึ้นเกี่ยวกับความแตกต่างระหว่างพวกเขา


15

$location.path('/configuration/streaming'); สิ่งนี้จะทำงาน ... ฉีดเซอร์วิสตำแหน่งในคอนโทรลเลอร์


13

ฉันใช้รหัสด้านล่างเพื่อเปลี่ยนเส้นทางไปยังหน้าใหม่

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

และฉีด $ window object ในฟังก์ชั่นคอนโทรลเลอร์ของฉัน


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

6

ใน 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/"; 

4

ฉันประสบปัญหาในการเปลี่ยนเส้นทางไปยังหน้าอื่นในแอพเชิงมุมเช่นกัน

คุณสามารถเพิ่มสิ่ง$windowที่ Ewald แนะนำไว้ในคำตอบของเขาหรือถ้าคุณไม่ต้องการเพิ่ม$windowเพียงเพิ่มการหมดเวลาและมันจะใช้ได้!

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

2

วิธีง่าย ๆ ที่ฉันใช้คือ

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

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
   }

})();

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

0

หากคุณต้องการใช้ลิงก์จากนั้น: ใน html มี:

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

ในไฟล์ typescript

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

}

ฉันหวังว่าคุณจะเห็นตัวอย่างนี้มีประโยชน์สำหรับฉันพร้อมกับคำตอบอื่น ๆ


โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.