gpt4 book ai didi

javascript - angularjs 替换用 angular.copy() 复制的对象中的换行符

转载 作者:行者123 更新时间:2023-12-03 06:05:36 25 4
gpt4 key购买 nike

我正在尝试替换对象属性中的所有换行符,该属性正在使用 json 对象中的 angular.copy 填充,但由于某种原因无法修改该值。

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

输出仍然是:hi\nhow\nare\nu\n

但是如果我在变量中设置这个输出

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

输出是:hi
how
are
u
如预期。

基本上,我正在尝试做这样的事情:

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

在 View 中:

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

尝试在 View 中获得正确的输出:

“嗨,你好吗”

有什么想法为什么它不起作用吗?

jsfiddle 示例:jsfiddle

最佳答案

*注意,我正在使用原始问题评论中提供的 jsfiddle。

基本上,您正在使用 angular.copy错了。

根据here的 Angular 文档:

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

您正在尝试复制 string 。解决方案是复制整个对象,然后使用正则表达式替换 \n<br/>

你的代码:

   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/>'));
}

工作代码(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/>')
}

关于javascript - angularjs 替换用 angular.copy() 复制的对象中的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39564431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com