Last active
January 6, 2019 07:31
-
-
Save mrzmyr/706d5322d91956308bd8 to your computer and use it in GitHub Desktop.
AngularJS – readmore directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('app', []) | |
.filter('truncate', function () { | |
return function (text, length, end) { | |
if (isNaN(length)) { | |
length = 10; | |
} | |
if (end === undefined) { | |
end = '...'; | |
} | |
if (text.length <= length || text.length - end.length <= length) { | |
return text; | |
} else { | |
return String(text).substring(0, length-end.length) + end; | |
} | |
}; | |
}) | |
.directive('readMore', function($filter) { | |
return { | |
restrict: 'A', | |
scope: { | |
text: '=readMore', | |
labelExpand: '@readMoreLabelExpand', | |
labelCollapse: '@readMoreLabelCollapse', | |
limit: '@readMoreLimit' | |
}, | |
transclude: true, | |
template: '<span ng-transclude ng-bind-html="text"></span><a href="javascript:;" ng-click="toggleReadMore()" ng-bind="label"></a>', | |
link: function(scope /*, element, attrs */) { | |
var originalText = scope.text; | |
scope.label = scope.labelExpand; | |
scope.$watch('expanded', function (expandedNew) { | |
if(expandedNew) { | |
scope.text = originalText; | |
scope.label = scope.labelCollapse; | |
} else { | |
scope.text = $filter('truncate')(originalText, scope.limit, '...'); | |
scope.label = scope.labelExpand; | |
} | |
}); | |
scope.toggleReadMore = function () { | |
scope.expanded = !scope.expanded; | |
}; | |
} | |
}; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- description is defined in your controller --> | |
<p | |
read-more="description" | |
read-more-limit="100" | |
read-more-label-expand="More" | |
read-more-label-collapse="Less"> | |
</p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment