如何从Angular.js内联模板的脚本标签内打印到console.log?

Mel*_*ssa 13 html javascript debugging console angularjs

我正在尝试Angular.js的内联模板.我希望有一种方法可以在呈现html页面时通过打印到控制台来调试Angular对象.

内联模板将html模板放在脚本标记内.例如:

<script type="text/ng-template" id="/htmlpage.html">
  <div class="page-header">
    <h1>Title</h1>
  </div>
  <!-- everything else here is html too -->
</script>
Run Code Online (Sandbox Code Playgroud)

这很棘手,因为脚本标签内的东西不再是JavaScript了.所以我不知道如何使用内联模板打印到htmlpage.html内的控制台.

我已经尝试但是嵌套脚本标记失败了:

<script type="text/ng-template" id="/htmlpage.html">
  <!-- html page template Angular stuff before is okay -->

  <script>console.log("this line DOESN'T SHOW UP anywhere");</script>

  <!-- html page template Angular stuff AFTERWARDS ALL FAIL-->
</script>
Run Code Online (Sandbox Code Playgroud)

我也试过抛出一个裸的console.log,因为它在一个脚本标签内.

<script type="text/ng-template" id="/htmlpage.html">
  <!-- rest of html page template is okay -->

  console.log("this entire line gets output as text on the html page");

  <!-- rest of html page template is okay -->
</script>
Run Code Online (Sandbox Code Playgroud)

但整行,console.log("this entire line gets output as text on the html page");打印到html页面,而不是控制台!

T.G*_*lle 14

您可以通过ng-init在模板定义中调用控制器作用域中定义的一些调试函数来实现此目的.看这个例子.

假设模板是由定义的

<script type="text/ng-template" id="myTemplate.html">
  <div ng-init="log('In template: '+$index)">{{greet}} Melissa<div>
</script>
Run Code Online (Sandbox Code Playgroud)

你有一个控制器定义为

var app = angular.module('myApp', [])
  .controller('myController', ['$scope', '$log', function($scope, $log) {
    $scope.greetings = ["Hello", "Bonjour", "Guten tag"];
    $scope.log = function(message) {
      $log.debug(message);
    }
  }]);
Run Code Online (Sandbox Code Playgroud)

然后

<ul ng-controller="myController">
  <li ng-repeat="greet in greetings">
    <div ng-include src="'myTemplate.html'"></div>
  </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

应该在控制台中打印

在模板中:0
在模板中:1
在模板中:2

ng-init被称为每次模板实例的时间.我只记录范围中的一些可用值,例如循环中$index的索引ng-repeat.

这个例子.