如何在 ng-click 上设置活动类? [英] How to set active class on ng-click?

查看:22
本文介绍了如何在 ng-click 上设置活动类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

<div class="account-item"><div class="account-heading" ng-class="active"><h4 class="账户名称"><a href="#/Info" onclick="SetActiveAccountHeading(this);">7.@Translate("SYSTEM_INFO")

在角度我有这个:

$scope.active = "active";

但是我如何在点击时更改此设置,以便如果用户点击菜单后它会处于活动状态,如果再次点击它将不会处于活动状态?

解决方案

好吧,假设你有多个菜单项,你想根据点击来切换类,

您可以在控制器中创建一个数组,将菜单项表示为,

$scope.menuItems = ['Home', 'Contact', 'About', 'Other'];

分配默认选中的菜单项

$scope.activeMenu = $scope.menuItems[0];

创建一个函数来分配选定的菜单值,该函数将为$scope.activeMenu分配一个最后选择的菜单项.

 $scope.setActive = function(menuItem) {$scope.activeMenu = menuItem}

HTML

遍历 menuItems 数组并创建菜单.

ng-class中检查最后点击的菜单项是否等于repeat中的项.

如果单击菜单,则调用控制器中的 setActive() 函数并将菜单项名称作为参数传递.

这是演示

这是一个DEMO,没有ng-repeat

I have this:

<div class="account-item">
    <div class="account-heading" ng-class="active">
        <h4 class="account-title">
            <a href="#/Messages"  onclick="SetActiveAccountHeading(this);">
            7.    @Translate("SYSTEM_MESSAGES")</a>
        </h4>
    </div>
    </div>
    <div class="account-item">
       <div class="account-heading" ng-class="active">
           <h4 class="account-title">
              <a href="#/Info"  onclick="SetActiveAccountHeading(this);">
              7.    @Translate("SYSTEM_INFO")</a>
           </h4>
      </div>
   </div>

In angular i have this:

$scope.active = "active";

but how can i change this on click so if user click on menu once it would be active if again click it would be NOT active?

解决方案

Ok say you have multiple menu items and you want to toggle the class according to click,

you can create a array in the controller which represents the menu items as,

$scope.menuItems = ['Home', 'Contact', 'About', 'Other'];

assign the default selected ,menu item

$scope.activeMenu = $scope.menuItems[0];

create a function to assign the selected Menu value, this function will assign the $scope.activeMenu a last selected menu item.

 $scope.setActive = function(menuItem) {
    $scope.activeMenu = menuItem
 }

in HTML

loop through the menuItems array and create the menu.

in the ng-class check last clicked menu item is equal to item in the repeat.

if click on the menu then call setActive() function in the controller and pass the menu item name as an argument.

<div class="account-item" ng-repeat='item in menuItems'>
   <div class="account-heading" ng-class="{active : activeMenu === item}">
      <h4 class="account-title">
        <a href="#/Messages" ng-click="setActive(item)"> {{ item }}</a>
      </h4>
   </div>
</div>

here is the DEMO

here is a DEMO without ng-repeat

这篇关于如何在 ng-click 上设置活动类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆