简体   繁体   中英

angularjs replace newline from an object copied with angular.copy()

I am trying to replace all line breaks in an object property which is being filled using angular.copy from a json object but for some reason the value can not be modified.

angular.copy(data, vm.candidate);
console.log(vm.candidate.Comments.replace(/\n/g, '<br/>'));

The output is still: hi\\nhow\\nare\\nu\\n

But if I set this output in a variable

var xx = "hi\nhow\nare\nu\n";
console.log(xx.replace(/\n/g, '<br/>'));

The output is: hi
how
are
u
as expected.

Basically, I am trying to do something like this:

 vm.candidate.Comments=$sce.trustAsHtml(vm.candidate.Comments.replace(/\n/g, '<br/>'));

In the view:

<p ng-bind-html="candCtrl.candidate.Comments"></p>

Trying to get the right outoput in the view:

"hi how are u"

Any ideas why it is not working?

A jsfiddle example: jsfiddle

*Notice, I'm working with the jsfiddle provided in the comments to the original question.

Basically, you're using angular.copy wrong.

According to the angular docs at here :

[angular.copy] Creates a deep copy of source, which should be an object or an array.

You're trying to copy a string . The solution is to copy the entire object and then use your regex to replace \\n with <br/>

your code:

   function LoginController($scope) {
     $scope.car2 = {};
     $scope.car = { "ID": 3, "Comments": "hi\\nhow\\nare\\nu\\n","RatingID": 2,"Rating":"Unsure"};
     $scope.car2=angular.copy($scope.car.Comments.replace(/\n/g, '<br/>'));  
 }

working code ( jsfiddle ):

   function LoginController($scope) {
     $scope.car2 = {};
     $scope.car = { "ID": 3, "Comments": "hi\nhow\nare\nu\n","RatingID": 2,"Rating":"Unsure"}
     $scope.car2 = angular.copy($scope.car)
     $scope.car2 = $scope.car2.Comments.replace(/\n/g, '<br/>')
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM