2015-10-04 31 views
2

我想限制「ng-repeat」顯示JSON數據時顯示的字符數。這個應用程序在RoR框架內使用AngularJS。目前我有下面的代碼,其顯示每個「item.description」,但不限制在字符串中的字符數來的長度25.如何使用AngularJS限制字符串的字符

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重複」,但限於所顯示的的「item.description(S)」的金額,並沒有限制STR ING /內容。我按照這個問題的指示:https://docs.angularjs.org/api/ng/filter/limitTo

+1

在文檔中正常工作演示,那麼有什麼不同?創建一個複製問題的演示。我們必須重現這個 – charlietfl

+0

我認爲唯一的區別是我在Rails應用程序中使用AngularJS。這裏是該項目:https://github.com/ctpelnar1988/TimelessEsthetics – Ctpelnar1988

+0

你使用的是什麼版本?也許它比'limitTo'被引入的時間更早? – charlietfl

回答

5

有一種更好的方式來做到這一點

添加屬性stringprototype 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> 
..... 

這裏是一個DEMO

+1

這解決了這個問題很好,謝謝! – Ctpelnar1988

+1

:)很高興幫助你,我用演示更新答案請檢查:) –

+2

很棒的演示!會有很多人從你的回答中受益:) – Ctpelnar1988

4

這可以解決您的問題。不是最好的,但一個選項:

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

我還沒試過,但我認爲它可以工作。

+0

由於某種原因,當我實施:{{item.description | limitTo:25}} {{item.description.length> 25? '...':''}} AngularJS完全退出工作,顯示如下所示:Welcome,{{name}}。 – Ctpelnar1988

+1

@ Ctpelnar1988嗯好吧...我會尋找其他解決方案。 – yuro

+0

它爲我工作沒有任何問題,thanx – Haris