aWebDeveloper
aWebDeveloper

Reputation: 38352

How do i use $location in a normal function

I have a angular app where half is angular js and half is plane js like ajax. So how do i use $location inside that function without passing it as a function parameter.

function x() {
   $location.path('/error').replace();
}

Now i wish to know how to use $location inside a normal javascript function. Basically i have a function that is being called from at least 20 places. In that function i wish to do replacestate.

Upvotes: 0

Views: 85

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

You need use angular.injector that will provide and access to provider from outside.

angular.injector(['app']).get('$location')

For more information Refer this SO Answer

Update

You could directly apply injector on element, that will give access to all the service present inside that module.

angular.element('body').injector().get('$location'); //body can replace by your element.

Upvotes: 1

Abhishek Jain
Abhishek Jain

Reputation: 2977

I would recommend wrapping that function as a service. And change myFunction and x to a sensible name. Change app to whatever your app name is.

function x($location) {
   $location.path('/error').replace();
}

x.$inject = ['$location'];

angular.module('app').function('myFunction', x); 

Upvotes: 0

Related Questions