2014-12-02 17 views
8

Sto utilizzando AngularJS per creare una pagina di articoli con collegamenti per i dettagli dei singoli articoli. I link sono basati sull'ID per garantire che siano unici, ma vorrei che gli URL fossero il titolo con trattini (molto più SEO/user friendly) piuttosto che l'ID. Ecco l'esempio angolare in cui i dettagli del prodotto sono i titoli pulite:Imposta URL su Titolo friendly SEO con trattini invece di ID

http://angular.github.io/angular-phonecat/step-11/app/#/phones

miei URL attuali sono legati da ID modo che appaiano come articolo/66D5069C-DC67-46FC-8A51-1F15A94216D4

voglio mostrarli come titolo dell'articolo come articolo/inizio-investimento e assicurarsi che siano SEO friendly.

La mia preoccupazione è che se due articoli di autori separati hanno lo stesso titolo (ad esempio, informazioni sugli investimenti), otterrò degli errori se provo a collegare/cercare per titolo rispetto a un ID che è univoco per articolo.

Qui sono i miei controllori:

var pfcControllers = angular.module('pfcControllers', []); 

pfcControllers.controller('pfcCtrl', ['$scope', 'pfcArticles', function ($scope, pfcArticles) { 
$scope.articles = pfcArticles.query(); 
}]); 

pfcControllers.controller('pfcCtrl2', ['$scope', '$routeParams', 'pfcArticles', function ($scope, $routeParams, pfcArticles) { 
$scope.article = pfcArticles.get({ articleID: $routeParams.articleID }); 
}]); 

Ecco il mio router:

var pfcModule = angular.module('pfcModule', ['ngRoute', 'pfcServices', 'pfcControllers']); pfcModule.config(['$routeProvider', function ($routeProvider) { $routeProvider. when('/home', { templateUrl: './views/home.html'}). when('/categories', { templateUrl: './views/categories.html', controller: 'pfcCtrl' }). when('/article/:articleID', { templateUrl: './views/articles.html', controller: 'pfcCtrl2' }). otherwise({ redirectTo: '/home' }); }]); 

qui sono i miei due parziali:

Categories.html (più articoli)

<div class="row"> 
<div class="col-md-4"> 
    <h2>Heading</h2> 
    <table class="table table-striped"> 
     <tr> 
      <th>ID</th> 
      <th>Title</th> 
      <th>Category ID</th> 
      <th>Link</th> 
     </tr> 
     <tr ng-repeat="article in articles"> 
      <td>{{article.id}}</td> 
      <td>{{article.articletitle}}</td> 
      <td>{{article.articlecategoryid}}</td> 
      <td><a href="#articles/{{article.id}}">Link</a></td> 
     </tr> 
    </table> 
</div> 

article.html (singolo articolo)

<div class="row"> 
<div class="col-md-4"> 
    <h2>Heading</h2> 
    <table class="table table-striped"> 
     <tr> 
      <th>ID</th> 
      <th>Title</th> 
      <th>Category ID</th> 
      <th>Summary</th> 
     </tr> 
     <tr> 
      <td>{{article.id}}</td> 
      <td>{{article.articletitle}}</td> 
      <td>{{article.articlecategoryid}}</td> 
      <td>{{article.articlesummary}}</td> 
     </tr> 
    </table> 
</div> 

Ecco un esempio della mia uscita JSON:

[{"id":"66D5069C-DC67-46FC-8A51-1F15A94216D4","articletitle":"Start Investing","articlecategoryid":1,"articlesummary":"Investing is not gambling, but many people treat it with fear, excitement and apprehension like they are playing a game of chance. They act under the assumption that an investor was born with money and understands rules that are not known by anyone else. While it is true that some of the biggest risks hold the largest gains, you can take a controlled and planned approach. There is nothing wrong with a long term reasonable gain on an investment. Question: It seems so complicated, how does someone start investing? Answer: In fact, it is easy start investing, without taking giant risks, and with a plan in place. The key is \"3D Investing\"; Diversify, Dollar Cost Averaging, and Determination. Need motivation? Use The Investing Calculator to determine your future value with compound interest. ","articlelink":"http://www.thebudgetcalculator.com/start-investing.html"},{"id":"4E94D4A5-15A3-4D3D-BAD5-C1E9264145A2","articletitle":"Why Budget","articlecategoryid":2,"articlesummary":"A budget is one of the most overlooked, yet powerful tools in a financial plan. You have to know what you have, what you don't have, and follow a \"road-map\" in order to get where you want to be! If you stick to your budget, it will be the best friend you have, because a lot of financial stress comes from not knowing where your finances are, and not having a plan. In your budget is where you lay out your plan of how your dollars are spent, what debts are being paid down (read about debt), and how much you can save for the future. Question: So why do so few people actually sit down and do a budget? Answer: Many people just don't know where to start. ","articlelink":"http://www.thebudgetcalculator.com/why-budget.html"},{"id":"E1E90A53-1839-4F1E-9C69-EFD1F77DD322","articletitle":"Managing Debt","articlecategoryid":3,"articlesummary":"Debt is both physical and emotional, because it not only affects both all physical finances and value, but also weighs on us through stress and uncertainty. A lot of this uncertainty comes from not knowing where you stand each month, and that is why a budget is so important to determine what you can and cannot spend. But let’s be realistic, at some point in our lives most of us have debt, whether it is in the form of credit cards, student loans, mortgage, etc. Question: So if you have debt, how do you go about paying it off? Answer: There are many approaches to paying down debt, and here are there of them. ","articlelink":"http://www.thebudgetcalculator.com/managing-debt.html"},{"id":"102CC729-465B-4893-8374-0F30AA4FC751","articletitle":"Retirement Planning","articlecategoryid":4,"articlesummary":"The word retirement sounds relaxing, but if you did not save for your golden years you had better start hoping for a miracle. If this statement does not scare you, let’s put it into proper perspective. If you do not save for retirement you will be a burden upon your loved ones, your society, and yourself. This is probably the shortest section on thebudgetcalculator.com because it is the most straightforward. Participate in your company’s retirement plan, or get an IRA (Individual Retirement Account). IRA's are offered at most banks and brokerages. So if your company does not have a retirement plan or you are self-employed, do yourself and the world a favor by starting your retirement savings today! The younger your start, the more you have at retirement, because the money put into an retirement account has more time to gain value before you need the funds.","articlelink":"http://www.thebudgetcalculator.com/retirement-planning.html"},{"id":"03119912-D732-4C68-B41E-F34B28FCD20F","articletitle":"Investing Basics","articlecategoryid":1,"articlesummary":"Learn the investing basics using these resources and start investing today. Whether you are a beginner investor, or seasoned broker, it is always valuable to understand the fundamentals of investing.","articlelink":"http://www.theinvestingcalculator.com/investing-basics.html"}] 

ho bisogno di eseguire una sorta di riscrittura URL, e se sì, come faccio in Angular? C'è un altro modo per avere un link univoco con un ID, o altri semplicemente un collegamento al titolo?

+1

si prega di postare anche la configurazione di routing ... .quando() e .otherwise(), è possibile impostare parametri opzionali sulla rotta aggiungendo ":" e il nome del parametro. Inoltre, è possibile utilizzare $ location.search service in angular per impostare l'id sull'URL – SoluableNonagon

+0

var pfcModule = angular.module ('pfcModule', ['ngRoute', 'pfcServices', 'pfcControllers']); pfcModule.config ([ '$ routeProvider', function ($ routeProvider) {$ routeProvider quando ('/ home', {TemplateURL:..' ./views/home.html '}) quando ('/ categories ', {templateUrl:' ./views/categories.html ', controller:' pfcCtrl '}). quando ('/article /: articleID ', {templateUrl:' ./views/articles.html ', controller: 'pfcCtrl2'}). altrimenti ({redirectTo: '/ home'}); }]); – Kode

+0

Sembra che il tutorial angolare stia utilizzando il campo id ma il valore è in realtà un titolo stringa. Non un vero campo ID IMO. – Kode

risposta

2

I lo consiglio per aggiungere corrispondenza con un altro percorso, oltre alla rotta esistente

when('/phones/:phoneId', { 
    templateUrl: 'partials/phone-detail.html', 
    controller: 'PhoneDetailCtrl' 
    }). 
    when('/phones/:phoneId/:title', { 
    templateUrl: 'partials/phone-detail.html', 
    controller: 'PhoneDetailCtrl' 
    }) 

per il vostro caso, si possono avere i seguenti link che va alla stessa pagina.

<a href="http://my.url.com/articles/#66D5069C-DC67-46FC-8A51-1F15A94216D4">Start Investing</a> 

<a href="http://my.url.com/articles/#66D5069C-DC67-46FC-8A51-1F15A94216D4/Start+Investing">Start Investing</a> 

La seconda funziona esattamente lo stesso come il primo

+0

Come ottengo più routeparams nel mio controller? Attualmente sto usando questa sintassi: pfcControllers.controller ('pfcCtrl2', ['$ scope', '$ routeParams', 'pfcArticles', function ($ scope, $ routeParams, pfcArticles) { $ scope.article = pfcArticles.get ({articleID: $ routeParams.articleID, articleTitle: $ routeParams.articleTitle}); }]); – Kode

0

L'utilizzo di js per generare la pagina non è molto conforme a SEO ... e inoltre, perché è presente un attributo "article-link" nel JSON ..?

Se questo collegamento non è inutile, è sufficiente recuperare il contenuto html e analizzare l'output per creare l'oggetto del prodotto.

O, meglio, si dovrebbe rielaborare l'implementazione lato server perché se si è in grado di ottenere un HTML con una richiesta GET sulla http://www.thebudgetcalculator.com/start-investing.html allora si dovrebbe implementare allo stesso modo per JSON chiamate API come http://www.thebudgetcalculator.com/api/articles/start-investing

+0

Articelink è per un URL nel caso in cui vi siano ulteriori informazioni a cui collegarsi. La mia principale preoccupazione è avere due articoli con lo stesso titolo, da due autori separati. Ecco perché mi sono avvicinato all'ID perché è univoco per ID. Per il tuo punto, il minore dei mali potrebbe essere quello di ri-lavorare il back-end ...a meno che non ci sia un metodo sul resto chiama per collegare tramite il titolo dell'articolo dove ID = ID – Kode

+1

puoi rielaborare il back-end per avere un articolo con il titolo "Inizia a investire" ottenendo un URI come "start-investing" e poi se un altro articolo con lo stesso titolo scende creandogli un URI come "start-investing-2". O se è una questione di autore e un articolo ha un titolo unico/uri per autore e fa chiamate api via api/autore/brutto-articolo-titolo. – n00dl3

+0

Idee forti. Analizzerò meglio la pubblicazione della chiamata REST con la logica per aggiungere il titolo desiderato – Kode

1

È possibile utilizzare una delle seguenti opzioni, li ho ordinato da mia preferenza:

  1. basta utilizzare il formattato titolo in url e non aggiungere altro a meno che non ci sia una collisione tra i titoli. In caso di collisione nel titolo, utilizzare uno dei seguenti metodi per distinguerli. Il tuo percorso sarà simile a "/ articles /: formattedTitle". Se ci sono più articoli nel database con lo stesso titolo e non ci sono indicatori espliciti di quale scegliere, andare avanti e scegliere quello creato prima.
  2. Creare un nuovo campo denominato textKey e compilare automaticamente tale campo in modo univoco in base al titolo dell'articolo. per esempio. uno si tradurrà in http://my.url.com/articles/start-investing e il prossimo risultati in http://my.url.com/articles/start-investing-2. Il tuo percorso sarà simile a "/ articles /: textKey"
  3. Crea un nuovo campo chiamato discriminator con il valore predefinito di Null lo popola solo se si verifica una collisione nei titoli. per esempio. uno risulterà in http://my.url.com/articles/start-investing e il successivo in http://my.url.com/articles/start-investing/1. Il percorso sarà simile a "/ articles /: formattedTitle /: discriminator"
  4. aggiungere ID e titolo, ad es. uno si tradurrà in http://my.url.com/articles/start-investing/66D5069C-DC67-46FC-8A51-1F15A94216D4 e il successivo risultati in http://my.url.com/articles/start-investing/AAE5069C-ABCD-46FC-8A51-1F15A94213A5. Il percorso sarà simile '/ articoli /: formattedTitle /: id'
1

vorrei suggerire di utilizzare il nome utente dell'autore e l'URL, in modo che il percorso sarà simile

.when('/article/:userID/:articletitle', { 
    templateUrl: './views/articles.html', 
    controller: 'articleCtrl' 
    }) 

Ciò risolverebbe il problema del diverso autore con lo stesso titolo dell'articolo (ma ora ci sarebbe un problema se l'autore pubblicasse due articoli con lo stesso titolo. Per questo puoi inserire l'anno o il mese nell'URL per renderlo unico)

Inoltre puoi creare un'altra vista in cui l'autore può vedere tutti i suoi articoli (Percorso sarebbe come)

.when('/article/:userID', { 
    templateUrl: './views/allArticles.html', 
    controller: 'allArticleCtrl' 
    }) 
Problemi correlati