简体   繁体   English

如何使用title而不是id进行Angular Routing?

[英]How to make Angular Routing with title instead of id?

I am building a blog with angular and am currently working on the routes. 我正在建立一个有角度的博客,我目前正在路线上工作。 I have the routes working with routeParams but angular gives it a random number and the url ends like http://localhost/kensproblems/#/posts/2 我有路由使用routeParams但angular给它一个随机数,网址结束如http://localhost/kensproblems/#/posts/2

I want it to either automatically grab the title and use it as the parameter on the URL or use the property called id on the json file such as http://localhost/kensproblems/#/posts/title-of-post 我希望它能够自动获取标题并将其用作URL上的参数,或者使用json文件中名为id的属性,例如http://localhost/kensproblems/#/posts/title-of-post

Is this possible with $routeParams ? 这是可能的$routeParams

app.js app.js

angular.module('app', [
    'ngRoute',
    'app.controllers',
    'ui.router',
    'ngSanitize'
])

.config(['$routeProvider', '$urlRouterProvider', function($routeProvider, $urlRouterProvider){
    $routeProvider
    .when('/posts', {
        templateUrl: 'views/posts.html',
        controller: 'PostListController'
    })
    .when('/posts/:id', {
        templateUrl: 'views/singlepost.html',
        controller: 'PostDetailController'
    })
        .otherwise({
        redirectTo: '/'
    });
}]);

controllers.js controllers.js

angular.module('app.controllers', ['app.directives'])
    /* Controls the Blog */
    .controller('PostListController', ['$scope', '$http', function($scope, $http){
        $http.get('data/posts.json').success(function(response){
            $scope.posts = response;
        });
    }])

    .controller('PostDetailController', ['$scope', '$http', '$routeParams', '$sce', function($scope, $http, $routeParams, $sce){
        $http.get('data/posts.json').success(function(response){
            $scope.post = response[$routeParams.id];
            console.log($routeParams.id);
            console.log($scope.post.id);
        });
    }])

posts.html posts.html

<div class="container" id="postList">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div ng-repeat="post in posts | orderBy:post.date" class="post">
                <h2 class="blog-title"><a href="#/posts/{{posts.indexOf(post)}}">{{post.title}}</a></h2>
                <span class="date">Posted on {{post.date | date:'MMM dd, yyyy'}}</span>
                <div class="row top10">
                    <div class="col-md-8">
                        <div class="post-content">{{post.headline}}</div>
                        <a class="read-more" href="#/posts/{{posts.indexOf(post)}}">Read more</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

singlepost.html singlepost.html

<div class="container" id="singlePost">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <h1>{{post.id}}</h1>
            <h1>{{post.title}}</h1>
            <span class="date">Posted on {{post.date | date:'MMM dd, yyyy'}}</span>

            <h3>{{post.headline}}</h3>
            <div class="postContent" ng-bind-html="post.content"></div>
        </div>
    </div>
</div>

You will need to change two main things, first how the URLs are generated, and second how the post is recovered. 您需要更改两个主要内容,首先是如何生成URL,以及第二个如何恢复帖子。

Generate URL from title 从标题生成URL

Not any title will be valid as URL, so you need to use slugs . 没有任何标题作为URL有效,因此您需要使用slugs

In the view: 在视图中:

<a class="read-more" href="#/posts/{{getSlug(post.title)}}">Read more</a>

In the controller: 在控制器中:

$scope.getSlug = function(text){
  return text.replace(/\W+/g, '-');
};

Search post from slug 从slug搜索帖子

Currently, you are just fetching the post from the array as an index, which is conceptually wrong (you will notice this after remove one post). 目前,您只是将数组中的帖子作为索引提取,这在概念上是错误的(删除一个帖子后会注意到这一点)。 Instead, make a search through the array. 相反,搜索数组。 This will be really simple if you use lodash . 如果你使用lodash,这将非常简单。

Something like this would work: 像这样的东西会起作用:

$scope.post = _.find(response, function(post) {
  return post.title.replace(/\W+/g, '-') === $routeParams.id;
});

Stack Overflow won't let me comment yet so I'll post here. Stack Overflow不会让我评论,所以我会在这里发布。 I looks like your passing the index of the post in the array instead of one of the properties. 我看起来像是在数组中传递帖子的索引而不是其中一个属性。 Look at changing: 看看改变:

href="#/posts/{{posts.indexOf(post)}}"

To something like: 对于这样的事情:

ng-href="#/posts/{{post.title}}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM