I need to insert open graph meta tags on a particular page in an angular app.
These tags are different based on the news or video that the page has.
I tried adding a variable to the $rootscope. This variable will be populated with the meta tags when it is relevant.
Now here is my issue. As soon as this variable gets populated with the HTML string, they don't form a part of the head and are instead outputted to the body. I have searched for a day and could not find any viable solutions. Any help would be appreciated
If you are using ui-router, you can use
$stateChangeSuccess
to set dynamically meta description and other meta tags based on current state. You have to put custom meta description in each state defined in$stateProvider.state(...)
.You must have
<meta name="description" content="Default Description">
in HTML markup, then and thendocument.getElementsByTagName('meta')
will be able to return the meta description tag.I want to re-answer this question. Infact, all your need a directive. You should set all your meta values as an object such as :
{name:'keywords',content:'angularjs, directive,meta'}
If you want to add it on $rootScope it can be like this :
Then you can use object's keys as an attribute and theirs value. Repeat the directive and pass all your metas in it. If you dont want a clear html you can create an empty meta element in javascript and add attributes on it. Then replace the directive element's outerHTML with your the new meta element's outerHTML. You can check this page : Simple Dynamic Meta Tags in AngularJS
I created an Angular module that can be used to set meta tags dynamically using the
$routeProvider
route definitions.You can then set the meta tags in HTML like so
To set the title, description and og:image dynamically, you can inject
ngMeta
into your controllerSupport for more tags and ui-router are in the works.
I was having a similar problem with Apple's Smart App Banner. You may be able to apply a similar logic if you are still looking for an answer.
I set up a service that populates the urlArgument with the id as per this answer., and used it in the page controller.