如何使用 AngularJS 限制字符串的字符数
How to limit the characters of a string using AngularJS
我想限制在 "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)" 的数量,并且没有限制 string/content。我按照以下说明解决了这个问题:https://docs.angularjs.org/api/ng/filter/limitTo
这可以解决您的问题。不是最好的,而是一个选择:
{{ item.description | limitTo: 25 }}{{item.description.length > 25 ? '...' : ''}}
我没试过,但我认为它可以工作。
有更好的方法
向 string
的 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>
.....
这是一个DEMO
我想限制在 "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)" 的数量,并且没有限制 string/content。我按照以下说明解决了这个问题:https://docs.angularjs.org/api/ng/filter/limitTo
这可以解决您的问题。不是最好的,而是一个选择:
{{ item.description | limitTo: 25 }}{{item.description.length > 25 ? '...' : ''}}
我没试过,但我认为它可以工作。
有更好的方法
向 string
的 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>
.....
这是一个DEMO