{{ item.name ...">

Dynamic url routing with angular

I have something like this 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 a url with the name of each element like / bmw or / mercedes and the whole url use details.html to display information about the selected element. I am trying to figure out how I can do this.

+3


source to share


3 answers


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 :carId

using $ routeParams

+4


source


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 write the url in app.js like below:

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

      



And then to finish you just need to get the name of the element in the controller

ItemCtrl.js:

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

      

+2


source


You can define paths in your module like this:

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 a new view.

You can customize the view on the element, for example: <md-content ng-view=""></md-content>

0


source







All Articles