Javascript 自定义AngularJS指令未注册
我正在尝试在我的AngularJS网站中实现一些指令,以允许使用自定义页面标题/描述对其进行SEO缓存 我已经设置了一个模块(Javascript 自定义AngularJS指令未注册,javascript,angularjs,angularjs-directive,typescript,Javascript,Angularjs,Angularjs Directive,Typescript,我正在尝试在我的AngularJS网站中实现一些指令,以允许使用自定义页面标题/描述对其进行SEO缓存 我已经设置了一个模块(angular.module('website.directives',[])),它被包含在我的应用程序中(angular.module('website',[…'website.directives')))。我知道带指令的文件正在正确下载和运行。该文件如下所示: angular.module('website.directives').directive('viewTi
angular.module('website.directives',[])
),它被包含在我的应用程序中(angular.module('website',[…'website.directives'))
)。我知道带指令的文件正在正确下载和运行。该文件如下所示:
angular.module('website.directives').directive('viewTitle', function() {
restrict = 'E';
link($scope, element) {
console.log("Linking view title.");
var text = element.text();
element.remove();
$('html head title').text(text);
}
});
angular.module('website.directives').directive('viewDesc', function() {
restrict = 'E';
link($scope, element) {
console.log("Linking view description.");
var text = element.text();
element.remove();
$('html head meta[name=description]').attr('content', text);
}
});
export class ViewTitleDirective implements ng.IDirective {
restrict = 'E';
link($scope, element: JQuery) {
console.log("Linking view title.");
var text = element.text();
element.remove();
$('html head title').text(text);
}
}
export class ViewDescriptionDirective implements ng.IDirective {
restrict = 'E';
link($scope, element: JQuery) {
console.log("Linking view description.");
var text = element.text();
element.remove();
$('html head meta[name=description]').attr('content', text);
}
}
angular.module('website.directives').directive('viewTitle', () => ViewTitleDirective);
angular.module('website.directives').directive('viewDesc', () => ViewDescriptionDirective);
同时,在我的模板中,我或多或少地像您所期望的那样使用它们:
<view-title>My Website</view-title>
<view-desc>A short description of my website.</view-desc>
我最好的猜测是,您正在body标记中引导应用程序
eg: <body data-ng-app="app">
例如:
尝试将其移动到html标记
<html data-ng-app="app">
这将在应用程序DOM编译中包括您的
,并应允许您的指令在标题和内容标记中激发。语句“这将在标题之前初始化您的应用程序”不正确。它将使head驻留在根元素中,但肯定不会在DOM准备就绪之前初始化应用程序。@estus您是对的。谢谢你在描述中指出我的拙劣选择。更好的选择是“这将在应用程序DOM编译中包含您的应用程序…”。这就是当我好几天都无法入睡时所发生的事情!我正在更新我的答案以反映这一点。