user2994560
user2994560

Reputation: 1309

AngularJS - How to remove index from URL

This works fine for now with a url like test.com/#/album/0/the-slug-here, but I'm trying to achieve test.com/#/album/the-slug-here

<a ng-href="#/album/{{$index}}/{{project.slug}}">{{project.title}}</a>

(function() {
var app = angular.module('chp', ['ngRoute', 'projectControllers']);

app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/', {
        templateUrl: 'partials/directory.html',
        controller: 'ProjectsCtrl'
      }).
      when('/album/:id', {
        templateUrl: 'partials/album.html',
        controller: 'ProjectDetailCtrl'
      }).
      when('/album/:id/:slug', {
        templateUrl: 'partials/album.html',
        controller: 'ProjectDetailCtrl'
      }).
      otherwise({
        redirectTo: '/'
      });
  }]);

var projectControllers = angular.module('projectControllers', []);

projectControllers.controller('ProjectsCtrl', ['$scope', '$http',
  function ($scope, $http) {
    $scope.projects = albums;
    $scope.filters = { };
  }]);

projectControllers.controller('ProjectDetailCtrl', ['$scope', '$routeParams', '$sce',
  function($scope, $routeParams, $sce) {
    $scope.project = albums[$routeParams.id];
}]);

When I remove the id though and try to just link to the slug, it's not loading in the data. The only way I've gotten to work so far is by adding the 2nd route which includes both. Any way to get rid of the index in the url?

Upvotes: 1

Views: 434

Answers (1)

PSL
PSL

Reputation: 123739

You would need to remove both the routes with :id and replace with the one with :\slug and you can just filter the album from albums to get the index;

You can do:

In the router:

  when('/album/:slug', {
    templateUrl: 'album.html',
    controller: 'ProjectDetailCtrl'
  }).

In the controller

  function($scope, $routeParams, $sce) {
    albums.some(function(album, idx){
       /*Search for a match*/
       if(album.slug === $routeParams.slug){
         /*Match found, set album and its index and break out*/
         $scope.album = album;
         $scope.albumIdx = idx;
         return true;
       }
    });

Plnkr

Shim support for Array.some for older browsers here.

Upvotes: 1

Related Questions