javascript - 是否有用于阅读更多/更少文本的基本 Angular Directive(指令)

标签 javascript jquery angularjs

我一直在研究制作一个 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/

相关文章:

javascript - 等待一个函数返回一个值,然后再继续执行其他函数的其余命令

angularjs - 我可以在 Protractor 框架中重用/调用 Selenium-Java 框架中的现有 API 吗?

javascript - ionic,如何在谷歌地图上显示正确的信息窗口?

javascript - 将 ref 动态分配给 textarea,但它返回最后一个字段值。

当从选项列表中选择多个复选框时,复选框的 JavaScript 验证

javascript - JQuery UI 对话框 - 需要添加一个最小化按钮

javascript - 如何打印 enzyme 浅包装的内容

jquery - 如何随机化每个循环项和 jquery 中的 ajax/json 数据?

javascript - AngularJS:如何使用 $location.path() 发送参数

javascript - 图像 src 未出现在 View 中