AngularJS is rendering
as text not as a newline

后端 未结 5 1182
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-14 00:10

I am sure this has been asked before but I cannot find the answer.

I have an AngularJS script that is pulling from a DB and then rendering to content. Everything is

相关标签:
5条回答
  • 2020-12-14 00:33

    You can use \n to concatenate words and then apply this style to container div.

    style="white-space: pre;"
    

    More info can be found at https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

    <p style="white-space: pre;">
        This is normal text.
    </p>
    <p style="white-space: pre;">
        This 
      text 
      contains 
      new lines.
    </p>

    0 讨论(0)
  • 2020-12-14 00:46

    I've used like this

    function chatSearchCtrl($scope, $http,$sce) {
     // some more my code
    
    // take this 
    data['message'] = $sce.trustAsHtml(data['message']);
    
    $scope.searchresults = data;
    

    and in html I did

    <p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p>
    

    thats it I get my <br/> tag rendered

    0 讨论(0)
  • 2020-12-14 00:49

    I could be wrong because I've never used Angular, but I believe you are probably using ng-bind, which will create just a TextNode.

    You will want to use ng-bind-html instead.

    http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml

    Update: It looks like you'll need to use ng-bind-html-unsafe='q.category'

    http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe

    Here's a demo:

    http://jsfiddle.net/VFVMv/

    0 讨论(0)
  • 2020-12-14 00:55

    Why so complicated?

    I solved my problem this way simply:

      <pre>{{existingCategory+thisCategory}}</pre>
    

    It will make <br /> automatically if the string contains '\n' that contain when I was saving data from textarea.

    0 讨论(0)
  • 2020-12-14 00:56

    You need to either use ng-bind-html-unsafe ... or you need to include the ngSanitize module and use ng-bind-html:

    with ng-bind-html-unsafe

    Use this if you trust the source of the HTML you're rendering it will render the raw output of whatever you put into it.

    <div><h4>Categories</h4><span ng-bind-html-unsafe="q.CATEGORY"></span></div>
    

    OR with ng-bind-html

    Use this if you DON'T trust the source of the HTML (i.e. it's user input). It will sanitize the html to make sure it doesn't include things like script tags or other sources of potential security risks.

    Make sure you include this:

    <script src="http://code.angularjs.org/1.0.4/angular-sanitize.min.js"></script>
    

    Then reference it in your application module:

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

    THEN use it:

    <div><h4>Categories</h4><span ng-bind-html="q.CATEGORY"></span></div>
    
    0 讨论(0)
提交回复
热议问题