Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger AngularJS routing from javascript

I'm trying to write a simple app that incorporates authentication.

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';
}

When I run the above code, I can see that authentication is happening correctly and it executes window.location.href = '#/chat';. However, this does not trigger Angular's routing rules and therefore, it does not load the template that I have defined.

I think once I get hold of the Angular $location object, I can set the URL and hope Angular does the rest. What is the right way to trigger Angular routing from plain javascript?

like image 874
Guru Prasad Avatar asked Feb 11 '26 00:02

Guru Prasad


1 Answers

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

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

Credit @joakimbl angularjs redirect from outside angular

like image 126
Rogerio Soares Avatar answered Feb 13 '26 15:02

Rogerio Soares



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!