在Angular JS中优雅地错误输出模板变量

时间:2015-03-15 23:02:00

标签: javascript angularjs

当Angular应用程序中有一行代码导致错误时,整个模板都会损坏。

例如,此代码(当我们尝试将值分配给foo.bar时会导致错误):

<!doctype html>
<html ng-app="myApp">
  <head>
    <meta charset="utf-8">
    <title>My App</title>
  </head>
  <body>
    <div class="container" id="home" ng-controller="MainCtrl">
      <h1>Message: {{hello_msg}}</h1>
    </div>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.10/angular.js"></script>
    <script>
      var myApp = angular.module('myApp', ['myApp.controllers']);
      angular.module('myApp.controllers', []).
        controller('MainCtrl', ['$scope', function ($scope) {
          var hello_msg = 'Hello!';
          $scope.hello_msg = hello_msg;

          // malformed JS
          foo.bar = 'app breaks';
        }]);
    </script>
  </body>
</html>

完全破坏页面,它看起来像这样:

enter image description here

是否有一些配置选项可以添加到我的Angular应用程序中,以便页面更优雅地出错?具体而言,如果应用中存在错误,则{{}}中包含的模板中的变量根本不会显示。

1 个答案:

答案 0 :(得分:2)

更优雅地出错的一种方法是使用:

<div ng-bind-html="hello_msg">

{{hello_msg}}打破应用时,丑陋的foo.bar将无法显示。


请查看证明要点的this plunker


重要提示

要使用ng-bind-html代替大括号,您需要在模块中加入ng-sanitize