Search code examples
javascripthtmlangularjsjsppreview

Making preview in writing page using AngularJS


I want have a preview in my writing page just like here in StackOverFlow question writing.

Everytime i press enterkey in the textarea, it doesn't make new line but just a space.

Instead of typing >br< tag in the textarea, I want pressing enterkey as really making a new line in the preview area.

Please help me and Thank you.

here's my code

<html>
<script
	src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script
	src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>
<head>
<script>
	var app = angular.module("myApp", [ 'ngSanitize' ]);

	app.controller("myCtrl", function($scope) {
	});
</script>
</head>
<body>
	<div ng-app="myApp" ng-controller="myCtrl">
		<textarea ng-model="myText"></textarea>
		<p id="contentsPreview" ng-bind-html="myText"></p>
	</div>

</body>
</html>


Solution

  • Can be done with css

    #contentsPreview {
      white-space: pre;// or pre-line
    }
    

    Otherwise use a function or filter to replace \n with <br>

    $scope.n2br = function(str){
       return str.replace(/\\n/g, '<br>')
    }