SeanPlusPlus
SeanPlusPlus

Reputation: 9043

Gracefully error out template variables in Angular JS

When there is a line of code in an Angular application that causes an error, the entire template is broken.

For example, this code (which results in an error when we try to assign a value to 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>

Completely breaks the page, and it looks like this:

enter image description here

Is there some configuration option that I can add to my Angular app so that the page erorrs out more gracefully? Specifically, the variables in the templates that are wrapped in {{ and }}, do not display them at all if there is an error in the app.

Upvotes: 1

Views: 77

Answers (1)

Manube
Manube

Reputation: 5242

One way to error out more gracefully would be to use:

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

The ugly {{hello_msg}} would not display when the foo.bar breaks the app.


Please check this plunker that proves the point


IMPORTANT NOTE

To use ng-bind-html instead of the curly brackets, you need to include ng-sanitize in your module.

Upvotes: 2

Related Questions