【问题标题】:How to limit the characters of a string using AngularJS如何使用AngularJS限制字符串的字符
【发布时间】:2016-01-01 07:50:01
【问题描述】:

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

【问题讨论】:

  • 在文档演示中运行良好,那么有什么不同?创建一个复制问题的演示。我们必须设法重现这个
  • 我认为唯一的区别是我在 Rails 应用程序中使用 AngularJS。这是项目:github.com/ctpelnar1988/TimelessEsthetics
  • 你用的是什么版本?也许它比引入limitTo 时更早?
  • @charlietfl 我正在使用 gem“angular-rails”,但也有全局加载的角度。我相信是:angular@1.4.7

标签: javascript ruby-on-rails angularjs angularjs-limitto


【解决方案1】:

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

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

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

【讨论】:

  • 由于某种原因,当我实现时:{{ item.description | limitTo: 25 }}{{item.description.length > 25 ? '...' : ''}} AngularJS 完全停止工作,显示如下内容:Welcome, {{name}}。
  • @Ctpelnar1988 嗯好的...我会寻找其他解决方案。
【解决方案2】:

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

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

【讨论】:

  • :) 很高兴为您提供帮助,我会通过演示更新答案,请检查 :)
  • 很棒的演示!会有很多人从你的回答中受益:)
  • 多么棒的答案。简单有效。
猜你喜欢
  • 2016-03-02
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多