2016-03-24 7 views
3

Ich versuche, eine einfache App zu schreiben, die Authentifizierung enthält.Auslöser AngularJS Routing von Javascript

var chatApp = angular.module('chat-app', ['ngRoute']); 

chatApp.config(['$routeProvider', 
    function($routeProvider) { 
     $routeProvider. 
     when('/chat', { 
      templateUrl : 'static/html/partial/chat.html', 
      controller: 'chatCtrl' 
     }); 
    } 
]); 

window.onload = function() { 
    checkAuth(); 
}; 

function checkAuth() { 
    var userId = localStorage.getItem('chat-id'); 
    var userProfile = localStorage.getItem('chat-profile'); 

    if(!userId) { 
    // Show login dialog and handle authentication 
    // This is done for me by an external service (auth0) 
    userId, userProfile = authenticate(); // Abstracting away for simplicity 
    localStorage.setItem('chat-id', userId); 
    localStorage.setItem('chat-profile', JSON.stringify(userProfile)); 
    } 
    else { 
    userProfile = JSON.parse(userProfile); 
    } 
    angular.element($('html')).scope().nickname = userProfile.nickname; 
    // Now redirect to /chat 
    window.location.href = '#/chat'; 
} 

Wenn ich den obigen Code ausführen, kann ich sehen, dass die Authentifizierung geschieht richtig und es führt window.location.href = '#/chat';. Dies löst jedoch keine Routing-Regeln von Angular aus und lädt daher die von mir definierte Vorlage nicht.

Ich denke, sobald ich das Angular $location Objekt ergreife, kann ich die URL einstellen und hoffe, dass Angular den Rest erledigt. Was ist der richtige Weg um angulares Routing von einfachem JavaScript auszulösen?

Antwort

3
var e = document.getElementById('chat-app'); 
var $injector = angular.element(e).injector(); 

var $location = $injector.get('$location'); 
$location.path("/chat"); 

Kredit @joakimbl angularjs redirect from outside angular

+0

'redirect'. Das ist das Stichwort, nach dem ich hätte suchen sollen! –

0

habe ich versucht, diese und seine Arbeiten. Ich hoffe, dies löst Ihr Problem.

<HTML> 
 
    <HEAD> 
 
     <script language="javascript"> 
 
      function GotoPage(){ 
 
       alert('I am in'); 
 
       document.location.href = 'index.html#/login'; 
 
      } 
 
     </script> 
 
    </HEAD> 
 
    <BODY> 
 
     <input type="button" value="Route" onclick="javascript:GotoPage()">Go To Angular Page</input> 
 
    </BODY> 
 
</HTML>

Check the URL of Angular application