如何使用AngularJS限制字符串的字符

Ctp*_*988 2 javascript ruby-on-rails angularjs angularjs-limitto

我想限制"ng-repeat"显示JSON数据时显示的字符数.这个应用程序在RoR框架内使用AngularJS.目前我有以下代码显示每个"item.description",但不限制字符串中的字符数为25.

HTML:

<div ng-controller="MyController">
  <ul>
    <li ng-repeat="item in artists">
     {{item.description | limitTo:25}}
    </li>
  </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

控制器:

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

myApp.controller("MyController", function MyController($scope, $http){
$http.get("/assets/data.json").success(function(data){
    $scope.artists = data;
  });
Run Code Online (Sandbox Code Playgroud)

我还尝试将"limitTo:"选项放在"ng-repeat"中,但这限制了显示的"item.description(s)"的数量,并没有限制字符串/内容.我按照这些说明解决了这个问题:https://docs.angularjs.org/api/ng/filter/limitTo

K.T*_*ess 5

有一种更好的方法可以做到这一点

strings 添加属性prototype object,以截断字符串

/**
 * extends string prototype object to get a string with a number of characters from a string.
 *
 * @type {Function|*}
 */
String.prototype.trunc = String.prototype.trunc ||
function(n){

    // this will return a substring and 
    // if its larger than 'n' then truncate and append '...' to the string and return it.
    // if its less than 'n' then return the 'string'
    return this.length>n ? this.substr(0,n-1)+'...' : this.toString();
};
Run Code Online (Sandbox Code Playgroud)

这就是我们如何使用它 HTML

.....
<li ng-repeat="item in artists">
     // call the trunc property with 25 as param 
     {{ item.description.trunc(25) }}
</li>
.....
Run Code Online (Sandbox Code Playgroud)

这是一个DEMO

  • 很棒的演示!会有很多人从你的答案中受益:) (2认同)