I've been looking into making an angular directive that would shorten a paragraph or a div if it has more than a certain number of characters(115 for example).
I haven't been able to find anything that will work for me, I've seen the http://dotdotdot.frebsite.nl/ and that has worked for some people but I am trying to make it using an angular directive and not JQuery.
If there's any help that someone can offer, it would be greatly appreciated, i am essentially tapped out of ideas.
The is the way my view is setup:
<div class="Description"
<div class="Content">
<div data-ng-bind-html="item.Description"></div>
</div>
I had originally made it work by just having it as jquery like so but it wasn't advisable to just jquery and 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;
});
});
I think what you're looking for is ng-class
. You can use it to add and remove classes based on a Boolean expression, which is basically what you are doing with your jQuery implementation. For example:
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;
});
You can use a combination of ng-click
and interpolation to modify the more/less link.
Here is a fiddle that shows it working: https://jsfiddle.net/8xjxaz28/
A quick google showed this package which would seem to fill your need for specific character limit truncation.
https://github.com/lorenooliveira/ng-text-truncate
NOTE: I did not write/use that directive so I can't speak to it working properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With