Search code examples
angularjsangularjs-directiveui-sref

What are the pros and cons of ui-sref?


I'm starting to work on a legacy project using Angular 1.5 and it uses both href and ui-sref.

I don't really see the point of using the latter, especially for top menu.

Example

menu.html

<a ui-sref="expense-home">
    <i class="fa fa-money"></i>
    <translate>Expenses claims</translate>
</a>

app.route.js

.state('expense-home', {
    url: '/expenses',
    template: '<expenses-home></expenses-home>',
})

Question

Could you provide some pros and cons of ui-sref and scenarios where it is useful?


Solution

  • Pros:

    1. url abstraction

    The most important gain from using ui-sref is that you work on state name which is some abstraction over the url address.

    So when using ui-sref you're really independent of the actual urls, and e.g. if you ever decide to change them (which, belive me, really happens ;) ) you just change the .state configuration and all urls within your app change.

    This way you can also possibly localize your urls, and e.g. in some instances have ui-sref="contact" pointed at /contact-us while in others to /kontaktiere.

    2. independence from parameters order

    The other thing is that when you have to pass several parameters into your url (say, the url definition is users/:userId/albums/:albumId) you don't need to remember/care about the parameters' order and just use the object:

    <a ui-sref="albumDetails({userId: user.id, albumId: album})">
      {{album.name}}
    </a>
    

    3. uninterpolated value for href attr prevention

    Other than that, as the other answer pointed out, when you use href directly, there is a moment in your app's lifecycle when what the browser sees is <a href="{{ sth }}"> - Angular hasn't yet interpolated the expression - if you'd click on such link it'd try to point you to something like http://example.com/%7B%7B%20sth%20%7D%7D. ng-href, ui-sref (and most noticeably ng-src on images) prevents from this to happen since they are not something that gets interpreted by browsers.

    Cons:

    As for the cons - I have yet to encounter one :)