自定义AngularJS指令未注册

时间:2015-10-11 00:20:34

标签: javascript angularjs angularjs-directive typescript

我试图在我的AngularJS网站上实施一些指令,允许它通过自定义页面标题/描述进行SEO缓存。

我已经设置了一个模块(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);
    }
});

与此同时,在我的模板中,我或多或少地喜欢使用它们:

<view-title>My Website</view-title>
<view-desc>A short description of my website.</view-desc>

不仅没有删除文本而且标题/说明没有更新,但我的console函数中的link语句根本没有被调用。我不确定为什么我的指令根本就没用过。

如果您需要更多信息,我很乐意提供。谢谢!

编辑:道歉,我试图将我的指令从TypeScript转换为Javascript,以便人们更容易阅读,但第二次认为这是一个糟糕的主意。我应该刚刚提供了代码。那就是说,看起来像这样:

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);

1 个答案:

答案 0 :(得分:1)

我最好的猜测是你在body标签中引导你的应用程序。

eg: <body data-ng-app="app">

尝试将其移至html标记

<html data-ng-app="app">

这将在您的应用程序DOM编译中包含您的<head>,并且应该允许您的指令在标题和内容标记中触发。

相关问题