Dynamic url routing with angularjs

亡梦爱人 提交于 2019-12-10 15:55:00

问题


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.


回答1:


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




回答2:


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;
}]);



回答3:


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>



来源:https://stackoverflow.com/questions/30873413/dynamic-url-routing-with-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!