Angular textarea newline not working when ng-model is changed

I have a text area bound to a variable in the controller using ngModel. The problem is only the initialized value is displayed in the textarea with proper new line formatting . When I change value of the model that has \n, it shows the text \n rather than the expected new line. Has anyone encountered this before? I'm using Angular 1.2.28

Controller

ctrlFunction = function () {
return {
    restrict: 'AE',
    templateUrl: 'my/view/path.html',
    link: function (scope, element, attrs) {

        scope.text = '\nLOOP 100\n  WAIT 5\n  input hello\n  if 1\n    message\n  endif\nENDLOOP\nHANGUP\n\n\n\u0000';

        scope.changeText= function(){
                 scope.text='\nLOOP 100\n  WAIT 5\n  input hello\n  if 1\n    message\n  endif\nENDLOOP\nHANGUP\n\n\n\u0000';
            }
        }
    }
}

View

  <textarea class="form-control" ng-model="text"></textarea>
  <button ng-click="changeText()"></button>

Before clicking the button enter image description here

After enter image description here

EDIT:

I forgot to mention "&#13;" or "<br />" did not work either. In fact they did not work even during the initialization of the model

Upvotes: 1

Views: 7603

Answers (1)

dting
dting

Reputation: 39307

I can't reproduce your problem but if you are trying to display the text with \n characters as newlines you can put the expression into an element with style="white-space: pre;"

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

app.directive('myTextArea', function() {
  var startingText = "Starting text";
  return {
    restrict: 'AE',
    template: '<textarea class="form-control" ng-model="text"></textarea><div style="white-space: pre;">{{ text }}</div><div><button ng-click="changeText()">change</button></div>',
    link: function(scope, element, attrs) {
      scope.text = startingText;
      scope.changeText = function() {
        scope.text = '\nLOOP 100\n  WAIT 5\n  input hello\n  if 1\n    message\n  endif\nENDLOOP\nHANGUP\n\n\n\u0000';
      }
    }
  };
});
textarea.form-control {
  height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>

<div ng-app='app'>
  <my-text-area></my-text-area>
</div>

Upvotes: 2

Related Questions