angular.module('app', [])
.controller('TestController', function($scope) {
$scope.loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
})
.directive('showMore', function() {
return {
restrict: 'A',
transclude: true,
template: [
'<div class="show-more-container"><ng-transclude></ng-transclude></div>',
'<a href="#" class="show-more-expand">More</a>',
'<a href="#" class="show-more-collapse">Less</a>',
].join(''),
link: function(scope, element, attrs, controller) {
var maxHeight = 45;
var initialized = null;
var containerDom = element.children()[0];
var $showMore = angular.element(element.children()[1]);
var $showLess = angular.element(element.children()[2]);
scope.$watch(function() {
// Watch for any change in the innerHTML. The container may start off empty or small,
// and then grow as data is added.
return containerDom.innerHTML;
}, function() {
if (null !== initialized) {
// This collapse has already been initialized.
return;
}
if (containerDom.clientHeight <= maxHeight) {
// Don't initialize collapse unless the content container is too tall.
return;
}
$showMore.on('click', function() {
element.removeClass('show-more-collapsed');
element.addClass('show-more-expanded');
containerDom.style.height = null;
});
$showLess.on('click', function() {
element.removeClass('show-more-expanded');
element.addClass('show-more-collapsed');
containerDom.style.height = maxHeight + 'px';
});
initialized = true;
$showLess.triggerHandler('click');
});
},
};
});
.show-more-container {
overflow: hidden;
}
.show-more-collapse, .show-more-expand {
text-align: center;
display: none;
}
.show-more-expanded > .show-more-collapse {
display: inherit;
}
.show-more-collapsed > .show-more-expand {
display: inherit;
}
<script src="https://code.angularjs.org/1.5.8/angular.js"></script>
<div ng-app="app" ng-controller="TestController">
<div show-more>
All sorts of <strong>stuff</strong> can go in here.
{{ loremIpsum }}
<div>Even more divs</div>.
</div>
<div show-more>
This <strong>won't</strong> truncate.
</div>
</div>
私は、テキストが実際にオーバーフローした場合にのみ、「表示テキスト」ボタンを表示し、そうでない場合は、それを非表示にします。どうすればそれをすることができますか? @Benmj –
答えをありがとう、私は今私に正確な質問を私に頼んだ私のデザイナーにこれを転送する方法を愛する。しかし、スコープ変数とcssクラスに異なる名前を使用すると、あなたの例はさらに良くなります。プログラミングに精通していない人には、「ショー」はあなたが思うほど明確ではないかもしれません;-) –