2

我想限制“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>

控制器:

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

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

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

4

2 回答 2

5

有更好的方法来做到这一点

string向's添加属性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();
};

这就是我们如何使用它HTML

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

这是一个演示

于 2015-10-04T16:18:34.853 回答
4

这可以解决您的问题。不是最好的,而是一种选择:

{{ item.description | limitTo: 25 }}{{item.description.length > 25 ? '...' : ''}}

我没有尝试过,但我认为它可以工作。

于 2015-10-04T16:01:58.563 回答