简体   繁体   English

如何在AngularJS中动态增加/减少段落元素的高度?

[英]How do you increase/reduce the height of a paragraph element dynamically in AngularJS?

I need to increase the height of ap element when I click a "Show More" button, which then should say "Show less" and then reduce the size of the p element when I click the button again. 单击“显示更多”按钮时,需要增加ap元素的高度,然后应显示“显示较少”,然后再次单击该按钮时,减小p元素的大小。 What is the best way to do this in Angular? 在Angular中执行此操作的最佳方法是什么?

This is the structure of my paragraph and button - 这是我的段落和按钮的结构-

<p ng-bind="MyController.notes"></p>
<button class="button show-button" ng-click="MyController.showMore()">Show More</button>

Template 模板

 <div ng-init="more = false">
    <p ng-class="{'showMore': more, 'showLess': !more}">
        bla bla bla.
    </p>
    <button ng-click="more = !more">{{more ? 'Show Less' : 'Show More'}}</button>
 </div>

CSS CSS

 .showMore { height: auto; }
 .showLess { max-height: 100px; overflow: hidden }

I would use ng-class directive. 我会使用ng-class指令。 (documentation here: https://docs.angularjs.org/api/ng/directive/ngClass ) (此处的文档: https : //docs.angularjs.org/api/ng/directive/ngClass

So it would be something like toggling a class called "showMore" that you need to bind in the p element 因此,这类似于切换一个名为“ showMore”的类,您需要在p元素中进行绑定

<p ng-class="showMore">Stuff here</p>
<button ng-click="showMoreClick">{{ showMore ? 'Show Less' : 'Show More'}}</button>

And in css, just apply the styles you want with showMore. 在CSS中,只需在showMore中应用所需的样式即可。 ng-class works with an expression so showMore will either be true or false. ng-class与表达式一起使用,因此showMore将为true或false。 in the controller, you want to tie the click button to toggling the variable showMore...something like this: 在控制器中,您想将单击按钮绑定到切换变量showMore ...,如下所示:

$scope.showMore(false) // initializing showMore to false (minimized first)
$scope.showMoreClick = function () {
    $scope.showMore(!$scope.showMore()); // toggle showMore
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM