I stumbled upon a tutorial that introduced me to using a service for dynamic SEO metadata here:
However, I encountered an issue - It seems like the service is not accessible outside of the controller's view. <div ui-view></div>
Here is the implementation of the service I'm trying to use:
app.service('SeoMetaService', function() {
var metaDescription = '';
var metaKeywords = '';
var title = '';
return {
metaDescription: function() { return metaDescription; },
metaKeywords: function() { return metaKeywords; },
title: function() { return title; },
reset: function() {
metaDescription = '';
metaKeywords = '';
title = '';
},
setMetaDescription: function(newMetaDescription) {
metaDescription = newMetaDescription;
},
appendMetaKeywords: function(newKeywords) {
for(var i=0;i<newKeywords.length;i++){
if (metaKeywords === '') {
metaKeywords += newKeywords[i];
} else {
metaKeywords += ', ' + newKeywords[i];
}
}
},
setTitle: function(newTitle) { title = newTitle; }
};
});
Here is how it's used in the controller:
app.controller('WelcomeController',['$scope', 'SeoMetaService', function($scope, SeoMetaService) {
$(document).ready(function() {
var keywords = ["bla bla","bla bla blah"];
SeoMetaService.setTitle("title bla bla bla");
SeoMetaService.setMetaDescription("description bla bla bla");
SeoMetaService.appendMetaKeywords(keywords);
console.log(SeoMetaService.metaDescription());
console.log(SeoMetaService.metaKeywords());
});
}]);
This is what it looks like on the main page (one-page-app), simplified:
<html ng-app="MainPage">
<head>
<title>{{SeoMetaService.title()}}</title>
<meta name="description" content="{{ SeoMetaService.metaDescription() }}">
<meta name="keywords" content="{{ SeoMetaService.metaKeywords() }}">
<base href="/">
</head>
<body>
<div ui-view></div>
</body>
The issue at hand - I initially thought that angular services are singletons. However, even after running the controller and setting the data, it doesn't reflect in the HTML.
Any suggestions on resolving this problem?