I am currently developing a custom "collapseText" directive using AngularJS. The purpose of this directive is to display a specified maximum number of characters and provide a "Read More" option to expand the text if it exceeds the limit.
My goal is for this directive to support transcluding text, including expressions.
Here is an example of how I envision using the directive:
<collapse-text max-length="10">This text will be collapsed</collapse-text>
<collapse-text max-length="10">{{foo}}</collapse-text>
The template structure I have in place is as follows:
<span>{{lessText}}</span>
<span ng-if="overflow">
<span ng-if="!readMore" style="cursor:pointer" ng-click="toggleReadMore()">...(read more)</span>
<span ng-if="readMore">{{moreText}}</span>
</span>
Here is a snippet of my directive implementation:
'use strict'
angular.module('myModule')
.directive('collapseText', function($window){
return{
restrict: 'E',
scope: true,
transclude: true,
controller : function($scope){
$scope.toggleReadMore = function(){
$scope.readMore = true;
}
},
link: function(scope, element, attrs, ctrl, transclude){
scope.maxLength = attrs.maxLength;
/* 1. Evaluate transcluded element */
/* 2. Check transcluded element's length */
/* 3. Set lessText, moreText, readMore and overflow */
/* 4. Evaluate this directive's template */
console.log(transclude(scope.$parent, function(compiled){
scope.lessText = compiled.text().substring(0, scope.maxLength);
scope.moreText = compiled.text().substring(0, scope.maxLength);
scope.readMore = false;
scope.overflow = scope.moreText ? true : false;
return compiled.text();
}).text());
},
templateUrl: "templates/collapse-text-template.html"
}
});
I have encountered two specific issues while implementing this directive:
- SOLVED: The ng-if statements do not update after changes to the overflow and readMore variables, resulting in certain text fields not displaying.
- To resolve this, I adjusted the ng-if conditions to use "overflow === true", "readMore === false", and "readMore === true". However, the main issue regarding transcluded text evaluation remains unresolved.
- PENDING: The expression {{foo}} prints as "{{foo}}" instead of the actual content of foo.
I appreciate any guidance on resolving these challenges. Thank you for your assistance!