Making AngularJS SEO Friendly

Posted By Weston Ganger

I have read all over the internet that SEO and AJAX sites is a real pain. But finally I came across an article saying that Google’s bots now read full javascript.

To enable it you will only have to make one small change in your app configuration. Just turn on html5Mode.


angular.module('awesomeApp', ['ngRoute', 'ngResource', ...]
  .config(function ($routeProvider, $locationProvider) {
    ... other config ...
    $locationProvider.html5Mode(true);
  })
});

Now thats all that is truly needed to make it work for the Google Bots but we should also make your app do a couple other things for SEO purposes.

First we create a service to change the page title.


.service('PageTitle', function() {
  var title = 'MyAppName';
  return {
    title: function() { return title; },
    setTitle: function(newTitle) { title = newTitle; }
  };
});

Secondly we will add a service to change the meta tags. You can change this service to provide for whatever meta tags you want.


.service('Meta', function() {
  var metaDescription = '';
  var metaKeywords = '';
  return {
    metaDescription: function() { return metaDescription; },
    metaKeywords: function() { return metaKeywords; },
    reset: function() {
      metaDescription = '';
      metaKeywords = '';
    },
    setMetaDescription: function(newMetaDescription) {
      metaDescription = newMetaDescription;
    },
    appendMetaKeywords: function(newKeywords) {
      for (var key in newKeywords) {
        if (metaKeywords === '') {
          metaKeywords += newKeywords[key].name;
        } else {
          metaKeywords += ', ' + newKeywords[key].name;
        }
      }
    }
  };
});

Now we can edit the page header like so:


<title ng-bind="PageTitle.title()"></title>

<meta name="description" content="{{ Meta.metaDescription() }}">
<meta name="keywords" content="{{ Meta.metaKeywords() }}">


Related External Links:

Article Topic:Software Development - Angular

Date:July 23, 2015