Sahil kalra
Sahil kalra

Reputation: 9034

How to avoid hardcoding URLs (or Routes) in AngularJS ? (provide URL resolution)

As I am in learning phase of AngularJS, today I noticed one thing about the tutorials avaliable for it.

In the tutorials, the URLs used are hardcoded in the HTML and JS files.

For example: If I have my routes defined like this in my config:

// config.js        
$routeProvider.when("/", {          // Home Page
                templateUrl: basePageUrl,
                controller: "Home"
            }).when("/searches", {
                templateUrl: basePageUrl,   // Search Page
                controller: "SearchPage",
            })

Now in my home.html , if I want to create a link to searches page. I have to do the following:

<!-- home.html -->
<div>
  Hello Home
  <p> Go to <a href="#/searches">Searches</a> </p>  <!-- I had to hard code the link -->
</div>

So, I was looking for a solution so I don't have to hard-code the links in HTML or JS files.

More like, the urls resolution functionality that each Backend MVC framework provides.. e.g

  1. Django: {% url %} templetag for HTML and reverse() for python code
  2. Rails: <%= link_to %> tag for HTML etc..

Is there a URL resolution functionality provided by AngularJS or any plugin ?

Note: I can implement something similar by storing JS variables/object for urls, but that doesn't look a good design to me

Upvotes: 4

Views: 1859

Answers (1)

nickromano
nickromano

Reputation: 908

You can use UI-Router for this. It has named 'states' instead of hardcoded urls

https://github.com/angular-ui/ui-router

In your case you could use:

myApp.config(function($stateProvider, $urlRouterProvider) {

$stateProvider
  .state('home', {
    url: "/",
    templateUrl: "partials/home.html",
    controller: 'HomeController'
  })
  .state('searches', {
    url: "/searches",
    templateUrl: "partials/searches.html",
    controller: 'SeachController'
  });

And then reference it in your template as

<a ui-sref="searches">Searches</a>

This comes in handy when you want to handle more complicated urls

.state('book', {
  url: '/books/:bookID/',
  templateUrl: 'partials/book-detail.html',
  controller: 'BookController'
})

Link in a template

<a ui-sref="book({ bookID: book.id })">{{ book.title }}</a>

You can then access bookID in your controller using $stateParams.bookID

Upvotes: 4

Related Questions