fauverism
fauverism

Reputation: 1992

Carriage Return in an Array is causing Unexpected token error

I'm attempting to retrieve a string of text that becomes corrupted when a Carriage Return is present.

There is a multi-line input field that allows the user it hit enter and type on the next line. There is a button that allows the user to save the note.

The save is happening as so...

if (save) note = $('#annotation_textarea').val();

Navigating to another page in the SPA app causes an Unexpected token error.

I tried to convert the carriage returns to
a la RegEx.

note.replace(/(\r\n|\n|\r)/g,"<br />");

that didn't work.

Here's the code to reproduce the issue:

app.js

var mySceApp = angular.module('mySceApp', ['ngSanitize']);

mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
  var self = this;
  $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
    self.userComments = userComments;
  });
  self.explicitlyTrustedHtml = $sce.trustAsHtml(
      '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
      'sanitization.&quot;">Hover over this text.</span>');
});

html

<!doctype html>
<html ng-app="mySceApp">
  <head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-sanitize.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
  <body>

<div ng-controller="myAppController as myCtrl">
  <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  <b>User comments</b><br>
  By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  $sanitize is available.  If $sanitize isn't available, this results in an error instead of an
  exploit.
  <div class="well">
    <div ng-repeat="userComment in myCtrl.userComments">
      <b>{{userComment.name}}</b>:
      <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
      <br>
    </div>
  </div>
</div>


  </body>
</html>

Test Data

[
  { "name": "Carriage Return test",
    "htmlComment":
        "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  },
  { "name": "Bob",
    "htmlComment": "<i>Yes!</i>  Am I the only other one?"
  },
  { "name": "Hal",
    "htmlComment": "You,
     are
     not
     alone!"
  }
]

Here's a plnkr
http://plnkr.co/edit/RYReiYQfD0Vw8u0BeDVc?p=preview

Upvotes: 0

Views: 928

Answers (1)

Dalorzo
Dalorzo

Reputation: 20014

I am not entirely sure what is going. I think the the safest will be to use $sce service and parse as html like

$sce.parseAsHtml(someValue)

Here is the documenation about this service:

http://docs.angularjs.org/api/ng.$sce

Upvotes: 1

Related Questions