Dynamic meta tags in your AngularJS single page application
This is an Angular 1.x module. Angular2 module is available as ng2-meta
- Demo
- Install
- Getting Started
- Defaults
- Dynamic meta tags
- Support For Other Crawlers
- Debugging
- Websites using ngMeta
- Further reading
- Licence
vinaygopinath.github.io/ngMeta
via NPM:
npm install ng-meta --save
via Bower:
bower install ngMeta --save
via CDN:
https://cdnjs.cloudflare.com/ajax/libs/ng-meta/0.3.9/ngMeta.min.js
or download the file from dist.
-
Add
ngMeta
as a dependency of your module. ngMeta supports ui-router and ngRoute.angular.module('YourApp',['ngMeta']);
-
Add
meta
objects to your routes (ngRoute) or states (ui-router) and specify the meta tags appropriate to each view. Other thantitle
andtitleSuffix
, which are reserved properties that affect the title of the page, the tag properties can be named as per your choice..config(function ($routeProvider, ngMetaProvider) { $routeProvider .when('/home', { templateUrl: 'home-template.html', meta: { 'title': 'Home page', 'description': 'This is the description shown in Google search results' } }) .when('/login', { templateUrl: 'login-template.html', meta: { 'title': 'Login page', 'titleSuffix': ' | Login to YourSiteName', 'description': 'Login to the site' } }); ... });
N.B. if you wish to take advantage of ui-router's nested views and data inheritence, then you should specify your "meta" config underneath the "data" property like this
```
.state( 'services', { abstract: true, url: '/services', templateUrl: '/services/base.html', controller: 'servicesCtrl', data: { 'meta': { 'og:image': 'http://www.yourdomain.com/img/facebookimage.jpg', 'author': 'PawSquad' } } }
.state(
'services.vaccinations', {
url: '/vaccinations',
templateUrl: '/services/vaccinations.html',
controller: '',
data: {
'meta': {
'title': 'Pet Vaccinations - All You Need To Know | PawSquad',
'og:title': 'All You Need To Know About Pet Vaccinations',
'og:description': 'Useful information about Routine Vaccines and Boosters for dogs and cats, including start vaccines for puppies and kittens.',
}
}
}
In this way the metadata for the url /services/vaccinations would be
'meta': {
'og:image': 'http://www.yourdomain.com/img/facebookimage.jpg',
'author': 'PawSquad',
'title': 'Pet Vaccinations - All You Need To Know | PawSquad',
'og:title': 'All You Need To Know About Pet Vaccinations',
'og:description': 'Useful information about Routine Vaccines and Boosters for dogs and cats, including start vaccines for puppies and kittens.',
} ```
-
[Optional] Set the default values of meta tags during Angular's configuration phase. If the
meta
object of a route does not contain a specific tag, the default value is used instead.//Add a suffix to all page titles ngMetaProvider.useTitleSuffix(true); // On /home, the title would change to // 'Home Page | Best Website on the Internet!' ngMetaProvider.setDefaultTitleSuffix(' | Best Website on the Internet!'); //Set defaults for arbitrary tags // Default author name ngMetaProvider.setDefaultTag('author', 'John Smith');
-
Let
ngMeta
initialize by calling theinit()
function in the app.jsrun
blockangular.module('YourApp', ['ngRoute', 'ngMeta']) .config(function($routeProvider, ngMetaProvider) { .... }) .run(['ngMeta', function(ngMeta) { ngMeta.init(); }]);
-
Set the meta tags in your HTML file
<title ng-bind="ngMeta.title"></title> <!-- OR <title>{{ngMeta.title}}</title> --> <!-- Arbitrary tags --> <meta property="og:type" content="{{ngMeta['og:type']}}" /> <meta property="og:locale" content="{{ngMeta['og:locale']}}" /> <meta name="author" content="{{ngMeta['author']}}" /> <!-- OR <meta name="author" content="{{ngMeta.author}}" /> --> <meta name="description" content="{{ngMeta.description}}" />
Change app-wide behaviour and set default values to tags using these methods of ngMetaProvider
. These defaults can be overridden by defining equivalent properties in the route/state meta
object
angular.module('YourApp', [....,'ngMeta'])
.config(function(ngMetaProvider) {
ngMetaProvider.useTitleSuffix(true);
ngMetaProvider.setDefaultTitle('Fallback Title');
ngMetaProvider.setDefaultTitleSuffix(' | YourSite');
ngMetaProvider.setDefaultTag('author', 'John Smith');
});
Method | Default | Example |
---|---|---|
useTitleSuffix(boolean) Toggles the use of a title suffix. When enabled, the title suffix of the route (if available) or the default title suffix is appended to the title of all pages. |
false |
ngMetaProvider.useTitleSuffix(true); |
setDefaultTitle(String) Sets the default title for all routes. This serves as a fallback for routes that don't have a title property. Use this to customize titles for a few specific routes, letting other routes use the default title. |
undefined |
ngMetaProvider.setDefaultTitle('Spotify'); ngMetaProvider.setDefaultTitle('Generic Title'); |
setDefaultTitleSuffix(String) Sets the default title suffix for all routes. This serves as a fallback for routes that don't have a titleSuffix property. The default title suffix is relevant only when useTitleSuffix is set to true. |
undefined |
ngMetaProvider.setDefaultTitleSuffix(' - Site Name'); ngMetaProvider.setDefaultTitleSuffix(' - YourSite'); |
setDefaultTag(String, String) Sets the default value of any arbitrary tag. This serves as a fallback for routes that don't have a particular tag. |
N/A | ngMetaProvider.setDefaultTag('author', 'John Smith'); ngMetaProvider.setDefaultTag('ogImgUrl', 'http://example.com/img.png'); |
To change meta tags dynamically (when an item in a list is clicked, for example), inject the ngMeta
service into your controller and use one of the following methods:
angular.module('YourApp')
.controller(function(ngMeta) {
//These examples assume useTitleSuffix is enabled,
//and default titleSuffix is set to 'Playlist'
//Custom title and titleSuffix
ngMeta.setTitle('Eluvium', ' | Spotify'); //Title = Eluvium | Spotify
//default titleSuffix
ngMeta.setTitle('Eluvium'); //Title = Eluvium | Playlist
//Clear the default titleSuffix
ngMeta.setTitle('Eluvium',''); //Title = Eluvium
ngMeta.setTag('author', 'Matthew Cooper');
ngMeta.setTag('image', 'http://placeholder.com/abc.jpg');
ngMeta.setDefaultTag('author', 'Default author');
});
Note: Please use setTitle
to modify the title and/or titleSuffix and setTag
for all other tags.
Method | Description | Example |
---|---|---|
setTitle(String title, String titleSuffix) | Sets the current title based on the given params. When useTitleSuffix is enabled and titleSuffix is not provided, it uses the default titleSuffix. |
ngMeta.setTitle('Title', ' - TitleSuffix') ngMeta.setTitle('Title with default titleSuffix') ngMeta.setTitle('Title with no titleSuffix','') |
setTag(String tagName, String value) | Sets the value of an arbitrary tag, using the default value of the tag when the second param is missing. The value is accessible as {{ngMeta.tagName}} from HTML. Calling setTag with title or titleSuffix as tagName results in an error. Title must be modified using setTitle instead. |
ngMeta.setTag('author', 'John Smith') ngMeta.setTag('ogImage', 'http://url.com/image.png') |
setDefaultTag(String tagName, String value) | Sets the default value of an arbitrary tag, overwriting previously set default values, but not the value set dynamically (using setTitle /setTag ) or by the route/state. title and titleSuffix are accepted values. |
ngMeta.setDefaultTag('image', 'http://default-image-url.com'); ngMeta.setDefaultTag('title','Default title'); |
If you want to dynamically set your tags using ui-routers resolve (https://github.com/angular-ui/ui-router/wiki#resolve), this is possible as well:
resolve: {
data: function(..., ngMeta) {
....
ngMeta.setTitle();
ngMeta.setTag('description', '....');
ngMeta.setTag('image', '....');
}
},
meta: {
disableUpdate: true
}
The property disableUpdate: true
is required because ui-router will execute the resolve function before the $stateChangeSuccess event is fired. Setting disableUpdate: true
will prevent your tags from getting reset by the $stateChangeSuccess event listener.
While Google is capable of rendering Angular sites, other search engines (?) and crawler bots used by social media platforms do not execute Javascript. This affects the site snippets generated by sites like Facebook and Twitter. They may show a snippet like this one:
You can use prerendering services to avoid this issue altogether, or update the server config to generate and serve a simplified page with just the open graph meta data needed for the bots to create snippets. Michael Bromley's article, Enable Rich Sharing In Your AngularJS App has more information on how to do that.
TL;DR: ngMeta helps the Google crawler render your Angular site and read the meta tags. For other sites like Facebook/Twitter that can't render Javascript, you need to use pre-renderers or server redirects.
-
ng-inspector Chrome extension shows the tags set by ngMeta when a state/route is open
-
Facebook's Open Graph Object Debugger shows detailed information about your site's meta tags as well as a preview of the snippet shown when your site is shared.
- acloud.guru - AWS certification online learning platform
To list your website here, please make a PR and add your URL in this section of README.md in this format
"Site URL - Short description"
- AngularJS & SEO - finally a piece of cake
- Fetch as Google - Google Webmaster Tools
- Deprecating our AJAX crawling scheme - Google Webmaster Blog
- Open Graph protocol
Vinay Gopinath