Dynamic url routing with angularjs

7.4k views Asked by At

I have something like that in my code

<ul ng-model="services">
   <p ng-repeat="item in items"><b>{{ item.name }}</b> 
   </p>

I have for example 3 items: BMW, golf and mercedes I want to have an url with the name of each item, like /bmw or /mercedes and all url use details.html to show the details of the selected Item. I'm trying to understand how can I do this.

3

There are 3 answers

0
FreshWaterTaffy On

You can define paths within your module like so:

var myModule = angular.module('myModule', [])
    .config(['$routeProvider', '$httpProvider', '$locationProvider', '$mdThemingProvider',
        function ($routeProvider, $httpProvider, $locationProvider, $mdThemingProvider) {
            $routeProvider
                .when('/page1', {
                    templateUrl: "Views/Angular/Pages/page1.html",
                    contoller: "page1Ctrl"
                })
                .when('/page2', {
                    templateUrl: "Views/Angular/Pages/page2.html",
                    controller: "page2Ctrl"
                })
            .otherwise({ redirectTo: '/default' });

When the path is changed to 'page1' this module will load page1.html as the new view.

You can set up a view in an element such as: <md-content ng-view=""></md-content>

0
Clyde Lobo On

You can write a generic route like

.when('/car/:carId', {
  templateUrl: 'some/path/details.html',
  controller: 'someCtrl'
})

And then in the controller you can get the value of :carId using the $routeParams

0
FlavienBert On

You just need to code this :

<ul ng-model="services">
  <p ng-repeat="item in items"><a href="/items/{{item}}">{{ item.name }}</b> 
  </p>
</ul>

And then capture the url in your app.js just like below:

.when('/item/:itemName', {
  templateUrl: 'some/path/itemDetail.html',
  controller: 'ItemCtrl'
})

And then to finish, you just need to get the item name in your controller

ItemCtrl.js :

App.controller('ItemCtrl', ['$scope', '$routeParams',
    function($scope, $routeParams) {
        $scope.itemName = $routeParams.itemName;
}]);