Làm cách nào để chuyển hướng đến một trang khác bằng AngularJS?


171

Tôi đang sử dụng lệnh gọi ajax để thực hiện chức năng trong tệp dịch vụ và nếu phản hồi thành công, tôi muốn chuyển hướng trang sang url khác. Hiện tại, tôi đang làm điều này bằng cách sử dụng js đơn giản "window.location = reply ['message'];". Nhưng tôi cần thay thế nó bằng mã angularjs. Tôi đã xem xét các giải pháp khác nhau trên stackoverflow, họ đã sử dụng $ location. Nhưng tôi mới đến góc cạnh và gặp khó khăn để thực hiện nó.

$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
Tại sao bạn cần sử dụng góc cạnh cho điều đó? Bất kỳ lý do cụ thể? document.location là cách thích hợp và có thể hiệu quả hơn so với cách góc
casraf

Câu trả lời:


229

Bạn có thể sử dụng Angular $window:

$window.location.href = '/index.html';

Ví dụ sử dụng trong một contug:

(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
Tôi đã sử dụng $ window.location.href nhưng nó báo lỗi hàm không xác định $ window.location. Tôi có cần bao gồm bất kỳ sự phụ thuộc cho điều này?
Farjad Hasan

3
Không, nhưng bạn có thể cần phải chèn $ window vào bộ điều khiển của mình. Xem câu trả lời chỉnh sửa của tôi.
Ewald Stieger

2
Window.location.href nó không $ window.location.href
Junaid

3
@ user3623224 - thực tế không phải vậy;)
Ben

12
@Junaid window.location.href dành cho đối tượng cửa sổ truyền thống, $ window.location.href dành cho đối tượng cửa sổ AngularJS $, tại đây: docs.angularjs.org/api/ng/service/$window
Mikel Bitson

122

Bạn có thể chuyển hướng đến một URL mới theo những cách khác nhau.

  1. Bạn có thể sử dụng $ window cũng sẽ làm mới trang
  2. Bạn có thể "ở bên trong" ứng dụng trang đơn và sử dụng $ location trong trường hợp bạn có thể chọn giữa $location.path(YOUR_URL);hoặc $location.url(YOUR_URL);. Vì vậy, sự khác biệt cơ bản giữa 2 phương thức là $location.url()cũng ảnh hưởng đến các tham số trong khi $location.path()không.

Tôi khuyên bạn nên đọc các tài liệu trên $location$windowđể bạn hiểu rõ hơn về sự khác biệt giữa chúng.


15

$location.path('/configuration/streaming'); điều này sẽ hoạt động ... tiêm dịch vụ định vị trong bộ điều khiển


13

Tôi đã sử dụng mã dưới đây để chuyển hướng đến trang mới

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

và chèn đối tượng cửa sổ $ trong chức năng điều khiển của tôi.


12

Nó có thể giúp bạn !!

Mẫu mã 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

Trong AngularJS, bạn có thể chuyển hướng biểu mẫu của mình (khi gửi) sang trang khác bằng cách sử dụng window.location.href='';như dưới đây:

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

Đơn giản chỉ cần thử điều này:

window.location.href = "https://www.thesoftdesign.com/"; 

4

Tôi cũng gặp phải vấn đề khi chuyển hướng đến một trang khác trong một ứng dụng góc cạnh

Bạn có thể thêm $windownhư Ewald đã gợi ý trong câu trả lời của anh ấy hoặc nếu bạn không muốn thêm $window, chỉ cần thêm thời gian chờ và nó sẽ hoạt động!

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

2

Cách đơn giản tôi sử dụng là

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

2

Một cách tốt để làm điều này là sử dụng $ state.go ('statename', {params ...}) nhanh hơn và thân thiện hơn cho trải nghiệm người dùng trong trường hợp khi bạn không phải tải lại và khởi động toàn bộ cấu hình ứng dụng và công cụ

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

});

// tuyến đường

(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

Nếu bạn muốn sử dụng một liên kết thì: trong html có:

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

trong tập tin bản thảo

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

}

Tôi hy vọng bạn thấy ví dụ này hữu ích vì nó dành cho tôi cùng với các câu trả lời khác.


0

Sử dụng location.href="./index.html"

hoặc tạo scope $window

và sử dụng $window.location.href="./index.html"

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.