Inject Angular provider into a JS function

51 views
Skip to first unread message

mark goldin

unread,
Oct 19, 2015, 12:35:34 PM10/19/15
to AngularJS
I am trying to create a generic JS function that would navigate to a provided state.
Something like this:
function goToState(state) {
    var stateTo = angular.injector(['$state']);
    stateTo.go(state);
}

Does not work. Any idea?

Thanks

Luís Loureiro

unread,
Oct 20, 2015, 7:22:24 AM10/20/15
to AngularJS
Hi Mark.

Why don't you explicit inject the service at the top of your angularjs component?
Are you trying to use ui.router?
If you're using the ui.router you need to change the value passed to the injector, pass the name of the module, "ui.router".
angular.injector returns an $injector. To use the service you need to call get('$state').

Hope this helps.

Regards,
Luís Loureiro

mark goldin

unread,
Oct 20, 2015, 9:11:31 AM10/20/15
to AngularJS
I need it for non Angular component. Here is what I finally have:
function goToState(state) {
    angular.element(document).injector().invoke(function ($state) {
        $state.go(state);
    });
}
Seems like working.

--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/WikWxMILSWo/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Luís Loureiro

unread,
Oct 20, 2015, 11:41:15 AM10/20/15
to AngularJS
Cool! Nice to hear that you solved your problem!

Regards,
Luís Loureiro
Reply all
Reply to author
Forward
0 new messages