Simple Dynamic Meta Tags in AngularJS

Many of AngularJS developer’s problem is writting a clear metas for search engine robots. When we add a meta in header tag, it must be clear and has none unnecessary attributes on them.

When we use AngularJS’ ng-repeat directive, it create some unnecessary attributes and classes on meta tags.

For example :

As the example, there is an ugly output for robots and this method is not practice to set dynamic attributes on metas. Now we will write a dynamic meta directive in AngularJS.

Firstly we have to define our meta object model on JavaScript side as a $rootScope value. On the object keys must be same with attribute names and key values as attribute values. For example :

Ok, now we set our model as an array and include three object. First and second objects has a regular type. But third one can make you confused. As you see in model, our meta tags’ attributes can be called different names. So we should create our directive as providing dynamic key names.

Firstly, I want to define my angular module as a variable which called myApp.

We crated our angular module and set a controller. Then, we defined our meta model on $rootScope object. Now, we will create our directive which provide dynmic metas to us.

On the first step, I want to define a function variable as link, then create directive and use it:

As you see in the example; I create an directive with dynamicMeta name. I want to tell you what I do in these codes.

Firstly I created a meta element thanks of angular.element() method and set it on meta variable.

Secondly, I use a for loop to get key names of my meta object wich I want as attirubte. When we get data from parent to directive, angular add a key  which called $$haskey. I want to pass it when I check my meta object key. So I used indexOf() method. If key is not include ‘$’ symbol, I add it as attirube on the meta element which I created above.

Finally, I replace my element’s outer HTML with new meta element’s outer HTML. But there is an important point. I add the line of replacing in a setTimeout() function. Because, we don’t want to block angular repeat when it works. If you want, you can create another directive to watch last rendering for replace html insteadof setTimeout().

Usage in HTML side like this:

Look at the demo : 

Leave a Reply

Your email address will not be published. Required fields are marked *