我是 angular.js
的新手.我正在尝试创建一个指令以在 <head>
中添加一些标题和元标记。部分 html 文档,但我遇到了一些麻烦。
我的 index.html
文档如下:
<!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>
我的 javascript 是:
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>'
};
});
当我打开检查器时,指令已移至 <body>
并且没有被模板替换:
如何在 header 中创建指令?
P.S.:最好有代码示例!
最佳答案
您的指令不需要进入 head
来设置标题。只需让您的指令注入(inject) $window
并设置 $window.document.title = 'your title'
。
UPDATE 这是更新元标记的方式。
为了更新元标记,我会使用这样的指令:
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);
连同设置元标签的服务:
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 already attached. Only one subscriber may be added as there can only be one instance of <head>');
}
}
// private
MetaTags.prototype._updateSubscriber = function(name, content) {
this.subscriber(name, content);
}
service('metaTags', MetaTags);
因此,在您的 head
标记中,您将包含属性 mm-meta-tags
。然后在您的 Controller 中,您将注入(inject) metaTags
服务并调用 addMetaTag
来更新标签。
关于javascript - 如何在文档的 <head> 部分创建 Angular 指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31277637/