2015-01-14 26 views
129

Sto utilizzando una chiamata ajax per eseguire funzionalità in un file di servizio e se la risposta ha esito positivo, desidero reindirizzare la pagina a un altro URL. Attualmente, lo sto facendo usando il js semplice "window.location = response ['message'];". Ma ho bisogno di sostituirlo con il codice angularjs. Ho cercato varie soluzioni su stackoverflow, hanno usato $ location. Ma io sono nuovo all'angolare e ho difficoltà a implementarlo.Come reindirizzare a un'altra pagina usando 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 
     }) 
+2

Perché è necessario utilizzare angolare per quello? Qualche ragione specifica? document.location è il modo corretto e probabilmente più efficiente del modo angolare – casraf

+1

Usa, $ location.path ('/' + response ['message']); – Ved

+0

@Ved Devo configurare $ location prima di questo? –

risposta

177

È possibile utilizzare angolare $window:

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

esempio in una contoller:

(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

Ho usato $ window.location.href ma dà un errore di funzione non definita $ window.location. Devo includere qualsiasi dipendenza per questo? –

+3

No, ma potrebbe essere necessario iniettare una finestra $ nel controller. Vedi la mia risposta modificata. –

+2

La sua window.location.href non $ window.location.href – Junaid

7

Potrebbe aiutare !!

L'AngularJs codice di esempio

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

$ location.path ("/"); ha funzionato per me – Johansrk

106

è possibile reindirizzare a un nuovo URL in modi diversi.

  1. È possibile utilizzare $window che sarà anche aggiornare la pagina
  2. Si può "stare dentro" la pagina singola applicazione e utilizzare $location nel qual caso si può scegliere tra $location.path(YOUR_URL); o $location.url(YOUR_URL);. Quindi la differenza fondamentale tra i 2 metodi è che $location.url() influisce anche sui parametri get mentre $location.path() no.

Mi raccomando di leggere la documentazione sul $location e $window in modo da ottenere una migliore comprensione delle differenze tra di loro.

12

$location.path('/configuration/streaming'); questo funzionerà ... iniettare il servizio di localizzazione controller

6

ho usato il codice qui sotto per reindirizzare alla nuova pagina

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

e iniettata finestra oggetto $ nella mia funzione di controllo.

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

Il modo più semplice che uso è

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

Un buon modo per farlo è usare $ state.go ('StateName', {params ...}) È più veloce e più amichevole per l'esperienza degli utenti nel caso in cui non si ha per ricaricare e bootsraping intera applicazione di configurazione e roba

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

}); 

// percorsi

(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

Se si desidera utilizzare un Link allora: nel codice HTML hanno:

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

nel file 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); 

}

Spero che questo esempio sia utile come lo è stato per me insieme alle altre risposte.

0

ho affrontato le questioni in reindirizzamento ad una pagina diversa in un app angolare così

è possibile aggiungere il $window come Ewald ha suggerito nella sua risposta, o se non si desidera aggiungere il $window, basta aggiungere un timeout e funzionerà!

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