on
Weird ellipsis in AngularJS…
Today at work I came across a strange issue.
I had written a function that would take some raw numeric data, then format it to be displayed. For instance, ‘1.234567’ might become ‘$1.23’.
In Angular I would normally just do plain old data binding like this:
$scope.adjustedValue = '$1.23'
<div></div>
That was working fine for most cases, but some of our values required special formatting:
$scope.adjustedValue = '<span class="prefix">$</span>1.23'
When I used ng-bind-html
to let me bind a variable containing HTML, however, an ellipsis was being appended to the end of my number.
<div ng-bind-html="adjustedValue"></div>
Instead of ‘$1.23’ as I expected, I was seeing ‘$1.23…’.
I thought there was maybe some CSS being applied that was inserting that ellipsis, but when I disabled CSS the rogue ‘…’ still appeared.
Binding with double curly braces behaved as expected, but using ng-bind-html
did not. Weird.
According to the docs for ngBindHtml
: “By default, the innerHTML-ed content will be sanitized using the $sanitize service.”
I tried bypassing the $sanitize
step to see if that would solve this ellipsis problem (I also had to inject $sce
into my controller):
$scope.adjustedValue = '<span class="prefix">$</span>1.23' $scope.bypassSanitize = -> $sce.trustAsHtml($scope.adjustedValue)
<div ng-bind-html="bypassSanitize()"></div>
That resolved the problem; the output no longer contained an ellipsis. Always kind of unsettling when you’re not exactly sure why something works…
The $sanitize
method will remove any unclean HTML from your bound variable, so forgo it with that caveat. Indeed, when I set $scope.adjustedValue = <script type="text/javascript">alert('hello');</script>
it was clear that arbitrary HTML was being bound. In this particular case our backend is scrubbing the possible output values, so I was able to move ahead using this solution.