1st option (HTML tag)
Wrap your {{message}} in the pre tag:
<pre>{{message}}</pre>
2nd option (scope function)
Replace spaces with using a scope method:
$scope.cleanup = function(message) {
return message.replace(/\s/g, ' ');
};
Now use in your HTML:
{{cleanup(message)}}
See a working example below
angular.module("sa", []).controller("foo", function($scope, $sce) {
$scope.cleanup = function(message) {
message = message || '';
// Need to trust as HTML to allow as HTML entity
return $sce.trustAsHtml(message.replace(/\s/g, ' '));
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sa" ng-controller="foo">
<input type="text" ng-model="message" />
<input type="range" min="1" max="100" ng-model="size" />
<hr>
<!-- Need to now always use "ng-bind-html" -->
<div style="font-size:{{size}}em;" ng-bind-html="cleanup(message)"></div>
</div>
3rd option (filter) - Recommended
Like Pankaj Parkar mentioned, you can create a filter as well:
angular.module("sa", []).filter("allowWhiteSpace", function($sce) {
return function(message) {
message = message || '';
// Need to trust as HTML to allow as HTML entity
return $sce.trustAsHtml(message.replace(/\s/g, ' '));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sa">
<input type="text" ng-model="message" />
<input type="range" min="1" max="100" ng-model="size" />
<hr>
<!-- Need to now always use "ng-bind-html" -->
<div style="font-size:{{size}}em;" ng-bind-html="message | allowWhiteSpace"></div>
</div>
https://docs.angularjs.org/api/ng/service/$sce
Even more, 4th Option (directive) - Recommended
You can make use of a directive:
angular.module("sa", []).directive("allowWhiteSpace", function($sce) {
return {
scope: {
value: '=allowWhiteSpace'
},
link: function($scope, element) {
$scope.$watch('value', function(message) {
message = message || '';
return element.html(message.replace(/\s/g, ' '));
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sa">
<input type="text" ng-model="message" />
<input type="range" min="1" max="100" ng-model="size" />
<hr>
<div style="font-size:{{size}}em;" allow-white-space="message"></div>
</div>
5th Option (CSS)
Like Utopic mentioned, you can use white-space: pre; as well. This will work like the <pre> tag:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<input type="text" ng-model="message" />
<input type="range" min="1" max="100" ng-model="size" />
<hr>
<div style="font-size:{{size}}em; white-space: pre;">{{message}}</div>
</div>
Choice is yours :-)