如何向 Angular 模板添加注释(针对开发人员,而不是在输出 HTML 中)?

问题描述 投票:0回答:4

我习惯了更流行的“胡子”样式模板,我可以在其中为同事添加评论:

{# The following code looks a bit odd, but here's why... #}

这些注释显然不会出现在输出中 - 因此用户看不到它们。我怎样才能在 Angular 中做类似的事情?

angularjs comments
4个回答
46
投票

Angular 没有内置模板注释支持。但是,您可以创建一个注释指令来支持它,如下所示。

app.directive('templateComment', function () {
    return {
        restrict: 'E',
        compile: function (tElement, attrs) {
            tElement.remove();
        }
    };
});

标记将是:

<template-comment>Put your comment here.</template-comment>

或者,您可以使用标准 html 注释,然后在部署之前将它们从生产代码中删除。

如果您想支持块注释,请考虑这个 grunt 任务 - https://github.com/philipwalton/grunt-strip-code 指定开始注释和结束注释,您的注释块将被删除生产代码的一部分,假设您将此任务添加到部署目标中。如果您不使用 Grunt,请将其用作构建过程的模型。 ....


32
投票

我意识到这个问题已经被提出七年多了,但它是“角度模板评论”的热门搜索结果之一,所以我们开始......

由于似乎仍然没有对(非 html)注释的模板语法支持,我发现最简单的方法是滥用对嵌入表达式中的一行 js 注释的支持。像这样:

{{ '' // my comment }}

空字符串文字 - 这使得它比现在更加丑陋 - 是必要的,因为没有它,角度编译器会抛出“TypeError 中的错误:无法读取未定义的属性“访问””,至少在 9.0.0 中是这样我正在使用的版本。

2021 年网络开发加油!


8
投票

您可以使用普通语法进行注释,而无需像

<!-- Order verification, and authorization -->
这样的特殊符号,然后您可以缩小html(grunt + htmlmin)

htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true,
          removeComments: true,
          ignoreCustomComments: [ /[<>\:\[\]\#]+/ ]

        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/**/*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

0
投票

我最近有同样的需求,并这样做了:

<div ng-if="false">
  <!-- Your comment -->
</div>

它只产生以下输出:

<!-- ngIf: false -->
© www.soinside.com 2019 - 2024. All rights reserved.