4

I have an ng-app and an ng-view. The app has multiple controllers.

From outside angular, legacy JS code, I'd like to redirect a certain controller.

var e = document.getElementById('mApp');
var scope = angular.element(e).scope();

scope.$apply(function() { scope.$location.path("/account/login"); });

I've tried $scope.$location and it's telling me $location is undefined so I must be doing something wrong.

3
  • Is this controller part of a nested view or does it have it's own URL? Commented May 8, 2013 at 21:05
  • I'm still learning angular so I apologize if I don't answer your question correctly. There is only one ng-view and it doesn't have nested controllers. Commented May 8, 2013 at 21:15
  • No prob - basically what I'm asking is what's the URL location of this controller? Because you could just do a normal redirect with window.location.hash Commented May 8, 2013 at 21:34

3 Answers 3

14

$location is an Angular service, it's not a property of $scope (unless you add it somewhere else). To get $location outside of your app you could use the $injector service - like this:

var e = document.getElementById('mApp');
var $injector = angular.element(e).injector();

var $location = $injector.get('$location');
$location.path("/account/login");
Sign up to request clarification or add additional context in comments.

1 Comment

I know that this is an old question, but the most elegant way I found to overcome this is to add a function to the angular object in your application's .run function. I just inject $location, and set angular.myRedirect = function(path) { $location.path(path); } This allows me to call angular.myRedirect('/home/stuff'); from anywhere that angular is loaded without giving IE fits. Adding stuff to the global scope is bad, but this prevents having multiple lines of code all over the place that may need to be changed at a later date.
4

Here's how I solved this. This will let you redirect in angular from outside of angular.

$('html').injector().get('$location').path("/where/you/want/to/go");
$('html').scope().$apply();

$('html') should be your root angular element (where ng-app is set)

Comments

0

Here's how I solved it, I have a vanilla Javascript function:

function navigateTo(url) {
    location.href = url;
}

which I overwrite in angular (application run):

$window.navigateTo = function (url) {
   $location.url(url);
   $rootScope.$applyAsync();
};

Hope this helps.

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.