Javascript 如何使用AngularJS限制字符串的字符
我想限制“ng repeat”显示JSON数据时显示的字符数。此应用程序在RoR框架内使用AngularJS。目前,我有以下代码显示每个“item.description”,但没有将字符串中的字符数限制为25 HTML:Javascript 如何使用AngularJS限制字符串的字符,javascript,ruby-on-rails,angularjs,angularjs-limitto,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}}
<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;
});
我还尝试将“limito:”选项放在“ng repeat”内,但这限制了“item.description(s)”的显示量,并且没有限制字符串/内容。我按照以下说明解决此问题:这可以解决您的问题。不是最好的,而是一种选择:
{{ item.description | limitTo: 25 }}{{item.description.length > 25 ? '...' : ''}}
我没有试过,但我认为它可以工作。有一个更好的方法可以做到这一点 将属性添加到
string
的prototype对象
,以截断字符串
/**
* 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>
.....
。。。。。
//使用25作为参数调用trunc属性
{{item.description.trunc(25)}
.....
这里有一个在文档演示中运行良好,那么有什么不同呢?创建一个复制问题的演示。我们必须用一种方法来重现这一点,我认为唯一的区别是我在Rails应用程序中使用AngularJS。这是项目:您使用的是什么版本?也许它比推出
limito
时更古老?@charlietfl我使用的是gem“angular rails”,但也有全局加载的angular。我相信:angular@1.4.7For当我实现:{item.description | limito:25}{{item.description.length>25?'…':'}}}AngularJS完全停止工作,显示如下内容:欢迎,{name}。@ctpelnark。。。我将寻找其他解决方案。:)很高兴能帮助您,我会用演示更新答案,请检查:)很棒的演示!将会有很多人从你的答案中受益:)多好的答案。简单有效。