Angular JS comment指令无法正常运行

时间:2016-09-23 04:00:18

标签: angularjs angularjs-directive

以下代码似乎不会从定义的指令中打印出文本:

<div ng-app="myApp">

    <!-- directive: devComment -->

</div>


<script>
    app.directive("devComment", function(){
                return{

                    restrict : "M",
                    replace : true,
                    template : " A comment made this print to html "

                };
            });
</script>

3 个答案:

答案 0 :(得分:1)

您的模板中的指令名称格式错误。它应该是

<!-- directive: dev-comment -->

(编辑:实际上,我刚刚对此进行了测试,对于注释指令,名称规范化似乎没有发生,因此真正的问题是没有根元素)

要使用replace,您的模板中也必须只有一个根元素。

angular.module('myApp', []).directive('devComment', function() {
  return {
    restrict: 'M',
    replace: true,
    template: '<span>A comment made this print to html</span>'
  };
});
<div ng-app="myApp">
    <!-- directive: dev-comment -->
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>

答案 1 :(得分:1)

您的模板必须只有一个根元素。请检查docs。所以您的模板应该如下所示

template : " <p>A comment made this print to html</p> "

工作人员here

答案 2 :(得分:1)

<div ng-app="myApp">
    <!-- directive: dev-comment -->
</div>
<script>
    app.directive("devComment", function(){
                return{
                    restrict : "M",
                    replace : true,
                    template : "<h3>A comment made this print to html</h3> "
                };
            });
</script>