javascript - How to create an Angular directive in the <head> section of a document? -
i new angular.js
. trying create directive add title , meta tags in <head>
section of html documents, having trouble.
my index.html
document following:
<!doctype html> <html ng-app="myapp"> <head> <meta charset="utf-8"> <base href="/"> <seo-title></seo-title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script> <script src="https://code.angularjs.org/1.4.1/angular-route.min.js"></script> <script src="/incl/js/myapp.js"></script> </head> <body > <div ng-view></div> </body> </html>
my javascript is:
var app = angular.module ('myapp', ['ngroute']); app.config(['$routeprovider', '$locationprovider', function($routeprovider, $locationprovider) { $routeprovider .when('/', { templateurl: 'routes/home.html'}) .when('/pagea', { templateurl: 'routes/pagea.html'}) .when('/pageb', { templateurl: 'routes/pageb.html'}) .otherwise({ redirectto: '/' }); $locationprovider.html5mode({ enabled: true }); }]); app.directive('seotitle', function() { return { restrict: 'e', template: '<title>{{seo.title}}</title>' }; });
when open inspector, directive has been moved <body>
, has not been replaced template:
how can create directives in header?
p.s.: code example great!
your directive not need go in head
set title. have directive inject $window
, set $window.document.title = 'your title'
.
update how can update meta tags.
for updating meta tags use directive this:
mmmetatags.$inject = ['metatags']; function mmmetatags(metatags) { return { restrict: 'a', link: function(scope, element) { metatags.metatags.foreach(function(tag) { addmetatag(tag.name, tag.content) }); metatags.subscribe(addmetatag); function addmetatag(name, content) { var tag = element[0].queryselector('meta[name="' + name + '"]'); if (tag) { tag.setattribute('content', content); } else { element.append('<meta name="' + name + '" content="' + content + '">'); } } } } } directive('mmmetatags', mmmetatags);
along service set metatags:
function metatags() { // private this._tags = []; // private this._subscriber; var self = this; object.defineproperty(this, 'metatags', { get: function() { return self._tags; }}); } metatags.prototype.addmetatag = function(name, content) { this._tags.push({ name: name, content: content }); this._updatesubscriber(name, content); } metatags.prototype.subscribe = function(callback) { if (!this.subscriber) { this._subscriber = callback; } else { throw new error('subscriber attached. 1 subscriber may added there can 1 instance of <head>'); } } // private metatags.prototype._updatesubscriber = function(name, content) { this.subscriber(name, content); } service('metatags', metatags);
so in head
tag include attribute mm-meta-tags
. in controller inject metatags
service , call addmetatag
update tags.
Comments
Post a Comment