如何在< head>中创建一个Angular指令文档的一部分? [英] How to create an Angular directive in the <head> section of a document?

查看:120
本文介绍了如何在< head>中创建一个Angular指令文档的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angular.js 的新手。我试图创建一个指令,在html文档的< head> 部分添加一些标题和元标记,但是我遇到了一些麻烦。



我的 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']); 
$ b 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> 并且尚未被模板取代: $ b

如何在头文件中创建指令?



PS:代码示例非常棒!

解决方案

您的指令不需要去在头部中设置标题。只需让你的指令注入 $ window 并设置 $ window.document.title ='your title'



更新这是您可以如何更新meta标签。 b
$ b

使用像这样的指令:

  mmMetaTags。$ inject = ['metaTags']; 
函数mmMetaTags(metaTags){

return {
restrict:'A',
link:function(scope,element){

metaTags.metaTags.forEach(function(tag){
addMetaTag(tag.name,tag.content)
});

metaTags.subscribe(addMetaTag);
$ b $ 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 +'>');

}
}
}

}

指令('mmMetaTags',mmMetaTags);

除了设置metaTags的服务外:

 函数MetaTags(){

// private
this._tags = [];

//私人
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。只有一个订户可能被添加,因为只能有一个< head>的实例');
}
}

// private
MetaTags.prototype._updateSubscriber = function(name,content){
this.subscriber(name,content) ;
}

服务('metaTags',MetaTags);

因此,在您的头部属性 mm-meta-tags 。然后在控制器中注入 metaTags 服务并调用 addMetaTag 来更新标签。

I am new to angular.js. I am trying to create a directive to add some title and meta tags in the <head> section of html documents, but I am having some trouble.

My index.html document is as 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 I open the inspector, the directive has been moved to the <body> and has not been replaced with the template:

How can I create directives in the header?

P.S.: A code example would be great!

解决方案

Your directive does not need to go in the head to set the title. Just have your directive inject $window and set $window.document.title = 'your title'.

UPDATE This is how you can update meta tags.

For updating meta tags I would use a Directive like 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 with a service to set the 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 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);

So in your head tag you would include the attribute mm-meta-tags. Then in your controller you would inject the metaTags service and call addMetaTag to update the tags.

这篇关于如何在&lt; head&gt;中创建一个Angular指令文档的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆