Angular指令作为评论不起作用

时间:2017-02-08 06:35:52

标签: angularjs

我引用了AngularJS文档,但无法获得评论指令"按照其提到的方式工作实际上遇到了错误。请找到以下详细信息:

HTML: -

fromDate.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    final Calendar newCalendar = Calendar.getInstance();
    datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
      public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        newCalendar.set(year, monthOfYear, dayOfMonth);
        datePickerDialog.getDatePicker().setMaxDate(newCalendar.getTimeInMillis() + 1000);
        datePickerDialog.getDatePicker().setMinDate(newCalendar.getTimeInMillis() - 1000);
        fromDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
      }
    }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
    datePickerDialog.show();
  }
});

JS: -

<!DOCTYPE html>
<html>
 <head>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
  <script type="text/javascript" src="JS/DirectiveAsComment.js"></script>
  <title>Directive as Comment</title>
 </head>
 <body ng-app="directiveAsCommentApp">
  <!-- directive:test-comment-directive -->
 </body>
</html>

错误:[$ compile:tplrt]指令模板&#39; testCommentDirective&#39;必须只有一个根元素。

请帮我解决这个问题..

2 个答案:

答案 0 :(得分:2)

When a directive is declared with template (or templateUrl) and replace mode on, the template must have exactly one root element. That is, the text of the template property or the content referenced by the templateUrl must be contained within a single html element. For example, <p>blah <em>blah</em> blah</p> instead of simply blah <em>blah</em> blah. Otherwise, the replacement operation would result in a single element (the directive) being replaced with multiple elements or nodes, which is unsupported and not commonly needed in practice.

更改此

template: 'this text is displayed because of "test-comment-directive" custom directive'

template: '<div>this text is displayed because of "test-comment-directive" custom directive</div>'

请参考:https://docs.angularjs.org/error/ $ compile / tplrt

答案 1 :(得分:1)

问题在于您的模板,将它们写入某些标签,例如或: 试试这个

<!DOCTYPE html>
<html>
     <head>
         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">      </script>
         <title>Directive as Comment</title>
     </head>
     <body ng-app="myApp">
         <!-- directive:test-comment-directive -->
    </body>
</html>

并在app.js中试试这个

var app = angular.module('myApp', []);

app.directive('testCommentDirective', function(){
    return {
        restrict: "M",
        replace: true,
        template: "<div>this text is displayed because of 'test-comment-directive' custom directive</div>"
           };
    });