AngularJS Nl2br Filter for Textarea Content Example

By Hardik Savani November 5, 2023 Category : Bootstrap jQuery Angular

Sometimes we require to display message conversion in your angularJS App, But if you are using textarea for write comment or something then text display on same like without line break. But we can display text with likebreak using nl2br(). we can use directly in nl2br() if we work on PHP But if we work on angulaJS then we can't use it directly Because it is not pre-define function.

So, we require to make custom helper or something, So in this example i created custom angular filter for nl2br, that way we can use it globally in angularJS app. we will use nl2br filter add like as bellow :

app.filter('nl2br', function($sce){

return function(msg,is_xhtml) {

var is_xhtml = is_xhtml || true;

var breakTag = (is_xhtml) ? '<br />' : '<br>';

var msg = (msg + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');

return $sce.trustAsHtml(msg);

}

});

Bellow i gave you full example and also demo, you can check and test it.

Example:

<!DOCTYPE html>

<html>

<head>

<title>angularjs nl2br example</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>

<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

<style type="text/css">

p{

padding: 10px;

background-color: #e1e1e1;

}

</style>

</head>

<body>


<div ng-app="mainApp" ng-controller="myController" id="mainController" class="container">

<form name="myform" ng-submit="submit()">

<div class="form-group">

<label>Comment:</label>

<textarea ng-model="myform.comment" class="form-control"></textarea>

</div>


<div class="form-group">

<strong>Print Comment:</strong>

<p ng-bind-html="myComment | nl2br"></p>

</div>


<div class="form-group">

<button class="btn btn-success">Check nl2br</button>

</div>

</form>

</div>


<script type="text/javascript">


var app = angular.module("mainApp", []);


app.controller('myController', function($scope, $timeout) {


$scope.myComment = '';


$scope.submit = function(){

$scope.myComment = $scope.myform.comment;

}


});


app.filter('nl2br', function($sce){

return function(msg,is_xhtml) {

var is_xhtml = is_xhtml || true;

var breakTag = (is_xhtml) ? '<br />' : '<br>';

var msg = (msg + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');

return $sce.trustAsHtml(msg);

}

});


</script>


</body>

</html>

Maybe it can help you...

Tags :
Shares