简体   繁体   English

如何从Angular中的元素获取类?

[英]how do you get a class off an element in Angular?

<div class="js-show-more">
    <p class="app-light-text">
         The factors of a number are all the numbers that divide into it. The highest common factor, HCF, of two
         or more numbers is the highest factor that divides into all the numbers. For example, what is the highest
         common factor of 24 and 36? The answer is 12. 12 is a factor of both 24 and 36 and it is the highest
         factor that they have in factors of a number are all the numbers that divide into it. The highest common factor, HCF, of two
         or more numbers is the highest factor that divides into all the numbers. For example, what is the highest
         common factor of 24 and 36? The answer is 12. 12 is a factor of both 24 and 36 and it is the highest
         factor that they have in common
    </p>
    <a ng-click="toggle($event)" class="js-show-more-toggle"></a>
</div>

// JS
scope.toggle = function (e) {
    console.log(scope);
    // $(e).parents('.js-show-more').toggleClass('open');
};

I'm trying to get the current class so I can then get the class above to add the class open to it. 我正在尝试获取当前的类,因此可以获取上面的类以向其中添加该类。

What is the best way to do this? 做这个的最好方式是什么?

So .js-show-more has the class .open when class .js-show-more-toggle is clicked. 因此, .open.js-show-more-toggle时, .js-show-more具有类.open I need this to work for duplicates of this code. 我需要它来处理此代码的重复项。

You should know the class based on a variable. 您应该基于变量知道类。

<div class="js-show-more" ng-class="{open:isOpen}>
    <p class="app-light-text">...</p>
    <a ng-click="isOpen = !isOpen" class="js-show-more-toggle"></a>
</div>


If using ng-repeat it gets even easier since ng-repeat automatically creates isolate scopes. 如果使用ng-repeat它将变得更加容易,因为ng-repeat自动创建隔离范围。 See example below: 请参见下面的示例:

 <div class="js-show-more" ng-repeat="item in items" ng-class="{open:item.isOpen}"> <p class="app-light-text">...</p> <a ng-click="item.isOpen = !item.isOpen" class="js-show-more-toggle"></a> </div> 

Simply extend each isolate scope! 只需扩展每个隔离范围!

您还可以使用jQuery ,因为这就是您正在使用的样子:

var className = $('js-show-more').attr('class');

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

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