我一直在研究制作一个 Angular Directive(指令),如果段落或 div 的字符数超过一定数量(例如 115 个),它会缩短该指令。
我没能找到适合我的东西,我看过 http://dotdotdot.frebsite.nl/这对某些人有用,但我正在尝试使用 Angular Directive(指令)而不是 JQuery 来实现它。
如果有人可以提供任何帮助,我将不胜感激,我基本上没有想法。
这是我的 View 设置方式:
<div class="Description"
<div class="Content">
<div data-ng-bind-html="item.Description"></div>
</div>
我最初只是通过将它作为 jquery 来使它工作,但不建议仅使用 jquery 和 angular
$(function () {
var maxHeight = 115;
var moretext = Localization.Shared.InstitutionProfileStrings.ShowMore();
var lesstext = Localization.Shared.InstitutionProfileStrings.ShowLess();
$('.__Description').each(function () {
var content = $(this).find(".__Content");
var anchor = $(this).find(".morelink");
if ($(content).height() > maxHeight) {
$(this).addClass("less");
$(anchor).html(moretext);
$(anchor).show();
}
else {
$(anchor).hide();
}
});
$(".morelink").click(function (e) {
e.preventDefault();
var parent = this.parentElement;
if ($(parent).hasClass("less")) {
$(parent).removeClass("less");
$(this).html(lesstext);
$(parent).addClass("more");
}
else if ($(parent).hasClass("more")) {
$(parent).removeClass("more");
$(this).html(moretext);
$(parent).addClass("less");
}
return false;
});
});
最佳答案
我认为您正在寻找的是 ng-class
。您可以使用它来添加和删除基于 bool 表达式的类,这基本上就是您对 jQuery 实现所做的事情。例如:
HTML:
<div ng-app="testapp" ng-controller="testctrl">
<div class="content" ng-class="{ less: hidden }">
Now is the time for all good men to come to the aid of the party.
Now is the time for all good men to come to the aid of the party.
Now is the time for all good men to come to the aid of the party.
Now is the time for all good men to come to the aid of the party.
</div>
<button ng-click="hidden = !hidden">{{hidden ? 'Show' : 'Hide'}}</button>
</div>
JS:
var app = angular.module('testapp', []);
app.controller('testctrl', function ($scope) {
$scope.hidden = true;
});
您可以结合使用 ng-click
和插值来修改更多/更少链接。
这是一个显示它工作的 fiddle :https://jsfiddle.net/8xjxaz28/
关于javascript - 是否有用于阅读更多/更少文本的基本 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34340830/