簡體   English   中英

如何讓 textarea 識別 AngularJS 中的新行?

[英]How do I make a textarea recognize new lines in AngularJS?

這是我嘗試將內容放入 angular 應用程序的一個簡單示例。 我有一個 textarea,它的文本將輸出到頁面的另一部分,如果在 textarea 中制作了換行符,我希望它們也可以轉移。 我已經嘗試過這里給出的答案,但是那個案例沒有使用 angular 並且它似乎對我不起作用(我通過使用{{sometext.replace(/\\n/g, "<br />")}}但這只是打破了表達式,只是將表達式顯示為一個帶花括號的字符串。我該如何解決這個問題?

 var app = angular.module('SomeApp', []); app.controller('SomeController', function($scope){ $scope.sometext = "Some text\\nMore text"; });
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app='SomeApp'> <div ng-controller='SomeController'> <textarea ng-model='sometext' rows='8' cols='25'></textarea> <p>{{sometext}}</p> </div> </body>

演示

上面的代碼有兩個問題:

  1. 您正在嘗試將\\n呈現為 html 頁面中的新行,html 無法將其識別為 html。

要解決此問題,您必須在渲染時通過創建過濾器替換字符串中的所有\\n 下面的過濾器使用一個正則表達式和值對數組來替換您要呈現的字符串。

爪哇腳本

  .value('HTMLIZE_CONVERSIONS', [
    { expr: /\n+?/g, value: '<br>' }
  ])

  .filter('htmlize', function(HTMLIZE_CONVERSIONS) {
    return function(string) {
      return HTMLIZE_CONVERSIONS.reduce(function(result, conversion) {
        return result.replace(conversion.expr, conversion.value);
      }, string || '');
    };
  });
  1. 第二個問題是過濾器不足以呈現html。 不要通過{{}}插入字符串本身,而是使用ng-bind-html因為它旨在將字符串呈現為 html。 此外,您必須包含ngSanitize模塊,以便ng-bind-html html 正確呈現 html 而不會出現問題。

HTML

<p ng-bind-html="someText | htmlize"></p>

筆記

您可以在HTMLIZE_CONVERSIONS數組中添加更多表達式和值對。

您可以使用另一個 textarea 代替 p

<textarea ng-model="sometext"> "you can type your input here"</textarea>

<textarea readonly> {{sometext}} </textarea> 

第一行獲取您的輸入,而第二行僅顯示輸入

<textarea [(ngModel)]="sometext"></textarea> <pre style="font-family: Arial;">{{sometext}}</pre>

這個適用於 Angular 8。

.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);
        }
    });

嘗試這個:

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

app.controller('SomeController', function($scope){
   $scope.sometext = "Some text\nMore text";
   $scope.sometext = $scope.sometext.replace(/\n/g, "<br />")
});

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

.filter('nl2br', 函數 ($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);

        }

    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM