Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS route helper

Any ideas how to build solution, that helps generate url in view in more convenient way, instead of hard-coding like that:

<a ng-href="#/Book/{{item.bookId}}/ch/{{item.id}}">Chapter {{item.id}}</a>

I want to use:

<a chapters="[item.bookId, item.id]">Chapter {{item.id}}</a>

So it checks routes and generates for each route specific directive.

I'm interested in the most generic solution as possible.

like image 775
dubadub Avatar asked Dec 14 '22 22:12

dubadub


1 Answers

I would highly recommend you make use of ui-router, and its $stateProvider.

var app = angular.module('yourModuleName', ['ui.router']);

app.config(function ($stateProvider) {
  $stateProvider
    .state('book', {
      url: '/Book/:bookId'
    })
    .state('book.chapter', {
      url: '/ch/:id'
    });
});

<a ui-sref="book.chapter({bookId: item.bookId, id: item.id})">Chapter {{item.id}}</a>

Something along those lines should do the trick. I'm not at all familiar with the other parameters of your application, but building dynamic URL's with passed in parameters to match up with a $state is a breeze.

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

ui-sref (directive): https://github.com/angular-ui/ui-router/wiki/Quick-Reference#ui-sref

like image 87
Kasper Lewau Avatar answered Jan 19 '23 08:01

Kasper Lewau