Using AngularJS RouteParams with Variable Routes

My AngularJS application has an item list view (basically a large list of items that the user can select) and an item detail . I have routes configured like this:

 angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives']). config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider. when('/', { templateUrl: 'partials/index', controller: indexCtrl }). when('/itemDetail/:id', { templateUrl: 'partials/itemDetail', controller: itemDetailCtrl }). otherwise({ redirectTo: '/' }); $locationProvider.html5Mode(true); }]); function itemDetailCtrl($scope, $http, $routeParams) { $http.get('/api/post/' + $routeParams.id). success(function(data) { $scope.post = data.post; }); } 

For the itemDetail/:id route, I want to have more than one identifier here: (/: id1 +: id2 +: id3). The system should work if the user selects one element, two elements or several elements.

Possible solution that I could not work with:

  • When a user selects multiple elements, my application registers unique id elements in an array
  • When going to the detailed view, the route becomes 'itemDetail/STRING , where STRING is a string made from the entire id in the array, with + between. For example: itemDetail/item1+item2+item3
  • In itemDetailCtrl I take a string, split it into + characters and create a new array, as before
  • Then I use ng-repeat to take those ids and load data from my database into my view.

This was the first decision that came to mind, but it seems rather laborious and not particularly elegant. Is there a better way to achieve this, and if so, how can I update itemDetailCtrl to display multiple identifiers?

+4
source share
1 answer

Since the URLs are not for a specific item and may have multiple, I would go with the URL more like itemDetail?item=item1&item=item2&item=item3 and then with $routeParams you should get $routeParams.item = [item1, item2, item3]

0
source

Source: https://habr.com/ru/post/1490215/


All Articles