3

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?

2 Answers 2

3
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

Sign up to request clarification or add additional context in comments.

1 Comment

redirect. That's the keyword I should've been looking for!
0

I tried this and its working. I hope this resolves your issue.

<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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.