【发布时间】:2018-02-21 09:44:15
【问题描述】:
我正在创建一个截断指令,如果字符超过 10 个,我会截断文本字符串。然后它将显示“...”。
我的目标是编写一个条件,如果字符少于 10 个,则删除“...”。如果有人对我如何实现这一点有任何想法,我会坚持这一点并接受建议。
这是我的代码:
var app = angular.module('myApp', []);
// Controller
app.controller('mainCtrl', function($scope) {
$scope.text = "John Doe Blah blah";
});
// Directive
app.directive('truncate', function() {
function link(scope, element, attrs){
scope.truncate = function(str){
if(str.length > 10) {
return 'truncate'
} else{
return 'notruncate'
}
}
}
// Write a condition to check if the username is < 10 characters to hide the ellipse
return{
restrict: 'A',
scope: {
input: '=',
maxCharacters: '=',
href: '=',
isShowMore: '='
},
template: '<h4 ng-init="limit=true;length=maxCharacters">{{input | limitTo: length}}<a ng-attr-href="#" ng-click="limit=!limit;length=limit?maxCharacters: \'\'">{{isShowMore?"Show More":"..."}}</a></h4>',
link: link
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<html ng-app='myApp'>
<body ng-controller='mainCtrl'>
<div href='true' input='text' is-show-more='false' max-characters='10' truncate=''></div>
</body>
</html>
【问题讨论】:
-
您可以使用 text-overflow: ellipsis 属性在不使用 angular 或 javascript 的情况下完成同样的事情。 developer.mozilla.org/en-US/docs/Web/CSS/text-overflow
标签: javascript angularjs haml truncate