Jak przekierować na inną stronę za pomocą AngularJS?


171

Używam wywołania ajax do wykonywania funkcji w pliku usługi i jeśli odpowiedź się powiedzie, chcę przekierować stronę do innego adresu URL. Obecnie robię to za pomocą prostego js "window.location = response ['message'];". Ale muszę go zastąpić kodem angularjs. Szukałem różnych rozwiązań na stackoverflow, używali $ location. Ale jestem nowy w kątowym i mam problem z jego wdrożeniem.

$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
Dlaczego musisz do tego używać kątów? Z jakiegoś konkretnego powodu? document.location jest właściwą drogą i prawdopodobnie bardziej wydajną niż metoda kątowa
casraf

Odpowiedzi:


229

Możesz użyć Angular $window:

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

Przykładowe użycie w kontrolerze:

(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
Użyłem $ window.location.href, ale daje to błąd o niezdefiniowanej funkcji $ window.location. Czy w tym celu muszę uwzględnić jakąkolwiek zależność?
Farjad Hasan

3
Nie, ale może być konieczne wstrzyknięcie $ window do kontrolera. Zobacz moją zredagowaną odpowiedź.
Ewald Stieger

2
Jego window.location.href, a nie $ window.location.href
Junaid

3
@ user3623224 - właściwie to nie jest;)
Ben

12
@Junaid window.location.href jest dla tradycyjnego obiektu okna, $ window.location.href dla obiektu okna AngularJS $, tutaj: docs.angularjs.org/api/ng/service/$window
Mikel Bitson

122

Możesz przekierować do nowego adresu URL na różne sposoby.

  1. Możesz użyć $ window, które również odświeży stronę
  2. Możesz „pozostać w” aplikacji z jedną stroną i użyć $ location. W takim przypadku możesz wybrać między $location.path(YOUR_URL);lub $location.url(YOUR_URL);. Tak więc podstawowa różnica między tymi dwiema metodami polega na tym, że $location.url()wpływa ona również na parametry get, podczas gdy $location.path()nie.

Poleciłbym przeczytanie dokumentów dalej $locationi $windowdzięki temu lepiej zrozumiesz różnice między nimi.


15

$location.path('/configuration/streaming'); to zadziała ... wstrzyknij usługę lokalizacji do kontrolera


13

Użyłem poniższego kodu, aby przekierować na nową stronę

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

i wstrzyknąłem obiekt $ window do mojej funkcji kontrolera.


12

To może ci pomóc !!

Przykład kodu 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

W AngularJS możesz przekierować swój formularz (po przesłaniu) na inną stronę, używając window.location.href='';poniższego:

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

Po prostu spróbuj tego:

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

4

Napotkałem problemy z przekierowaniem na inną stronę w aplikacji kątowej

Możesz dodać tak, $windowjak zasugerował Ewald w swojej odpowiedzi, lub jeśli nie chcesz dodawać $window, po prostu dodaj limit czasu i zadziała!

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

2

Używam prostego sposobu

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

2

Dobrym sposobem na zrobienie tego jest użycie $ state.go ('statename', {params ...}) jest szybsze i bardziej przyjazne dla użytkownika w przypadkach, gdy nie musisz przeładowywać i ładować całej konfiguracji aplikacji i innych rzeczy

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

});

// trasy

(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

Jeśli chcesz skorzystać z linku to: w html masz:

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

w pliku maszynopisu

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

}

Mam nadzieję, że ten przykład okaże się pomocny, ponieważ był dla mnie wraz z innymi odpowiedziami.


0

Za pomocą location.href="./index.html"

lub stwórz scope $window

i używając $window.location.href="./index.html"

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.