yancyzhao yancyzhao - 1 month ago 10
AngularJS Question

Angular ng-repeat <li> string line feed

  • view:

    <li ng-repeat='msg in msgs'>{{msg}}</li>


  • controller:

    msgs=['abc','a
    b
    v', '123']

    msgs.push('Something input from textarea, maybe has line feed')


  • wants:



    • abc

    • a
      b
      v

    • 123




  • but result line feed gone



    • abc

    • a b v

    • 123




  • try resolve

    try refactoring < li> label to <myli>

    app.directive('myli', function ($rootScope) {
    return {
    restrict: 'E',
    replace: true,
    template: "<li></li>",
    link: function(scope, element, attr) {
    element.append(scope.msg);
    }
    }
    });


    but not what i want, it just change initial data.

    if i push something to msgs with line feed, line feed will change to space.

    help me

  • Answer

    Use the CSS white-space property...

    angular.module('so', []).run(function($rootScope) {
      $rootScope.msgs = ['abc', `a
                 b
                 v`, '123'];
    
      $rootScope.msgs.push('Something input from textarea, maybe has line feed')
    });
    li {
      white-space: pre-line;
    }
    <ul ng-app="so">
      <li ng-repeat="msg in msgs">{{msg}}</li>
    </ul>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

    Comments