34

I have recently started using ionic framework, it has angular js in it. To navigate between screens, I was using $location.path and it's working great. However, in an example I've downloaded, I saw $state.go being used to redirect to some page. I would like to know the difference between the two.

1
  • but you're not going to tell him what those features are? Or provide a URL? Sep 20, 2015 at 7:21

3 Answers 3

51

The $location service is on the angular.js framework out of the box and allow you to manage location object (similar to that in pure javascript). The $state service is a part of ui-router module and allows you to manage routes in an advanced mode, throughout a state machine management of views.

If you use ui-router, you should prefer to use $state service to manage states/routes because state abstracts the concept of route and you could change the physical routes without changing states.

Besides that, more problems you could have if you run in hashbang mode, in particular in your html links. In this case it's preferable to use ui-sref rather than ng-href (or just href). In my opinion, you should always think in term of states rather than paths. Obviously you can mix the services if you know what you're doing

1
  • 7
    OP, this has a lot of upvotes. If you agree, then please award the answer which will help others who view this question in future. Sep 20, 2015 at 7:22
2

Thanks @wilver for answering it. As I dug deeper into angular and learned different ways of structuring my projects, I got to understand these states and paths better. And yes, I've found states much better than paths.

$state.go, which comes with $stateProvider - a provider by ui-router, will work based on state names. Major difference between previously inbuilt(now you need to include ngRoute) router and states is that "States can have nested states but with router it's not possible. And I suddenly realized that whole of Ionic framework is possible because of this concept - I was able to understand this while working on an angular web app based on ngRoute and ionic app based on ui-router.

Ionic works with app as basic state and all other screens defined as its sub states. That's why you see app.screen1, app.screen2 inside $stateProvider in app.js.

So when you have routes, you use $location.path("<routeUrl>") and when you have states, you use $state.go("<stateName>")

0

I use ionic and one of the differences that I have observed but not yet figured out why is that $location.path is much slower than $state.go

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.