简体   繁体   English

ng-click上的角活动类

[英]Angular active class on ng-click

In my angular app I have three buttons, each representing a different state. 在我的角度应用程序中,我有三个按钮,每个按钮代表不同的状态。

<ul class="handset-qty-tabs">
    <li ng-class="{'active': devices.length < 5 && tariffTypeSelection !== 'welcome'}">1 - 4 {{ params.device_name }}s</li>
    <li ng-class="{'active': devices.length >= 5}">5 - 19 {{ params.device_name }}s</li>
    <li>20 + {{ params.device_name }}s</li>
</ul>

The current rule for the tabs becoming active is based on the length of devices . 选项卡变为活动状态的当前规则基于deviceslength In addition to this though I want the buttons to be clickable and onclick, the clicked tab has the active class. 除此之外,尽管我希望按钮可单击和onclick,但clicked选项卡具有活动类。 There should only be one active class at one time between all three buttons. 三个按钮之间一次只能有一个活动班级。

Pretty standard, simple stuff but what's the best-practise Angular way to make this happen? 相当标准,简单的东西,但是实现这一目标的最佳实践Angular方法是什么?

in angular way you need to keep which tab is currently active and find a way to switch it with a function so the default value for the active tab and the function definition should be 以角度的方式,您需要保持哪个选项卡当前处于活动状态,并找到一种使用功能进行切换的方法,因此活动选项卡和功能定义的默认值应为

scope.activeTab = scope.devices.length < 5 && scope.tariffTypeSelection !== 'welcome' ? "first" : "second"; // only have first and second just implement the others.

//will bind this to the ng-click
scope.tabClick = function(tab) {
   scope.activeTab = tab;
};

the controller logic is ready now for the view; 现在,控制器逻辑已准备好用于视图;

<ul class="handset-qty-tabs">
    <li ng-class="{'active': activeTab === 'first' }" ng-click="tabClick('first');">1 - 4 {{ params.device_name }}s</li>
    <li ng-class="{'active': activeTab === 'second'" ng-click="tabClick('second');">5 - 19 {{ params.device_name }}s</li>
    <li>20 + {{ params.device_name }}s</li>
</ul>

this is really simple example of course if you can (or if you already have) build a tab array like below; 如果您可以(或如果已经拥有)构建如下所示的选项卡数组,那么这实际上是一个非常简单的示例;

scope.tabs = [{text: "1 - 4", isActive: true}, {text: "5 - 19", isActive: false}];
//don t forget to set isActive accroding to your rule also build texts properly
scope.tabClick = function(index) {
   angular.forEach(scope.tabs, function(t){t.isActive = false;});
   scope.tabs[index].isActive = true;
};

and similar to above example set the display and click with ng-repeat; 与上面的示例类似,设置显示并用ng-repeat单击;

<ul class="handset-qty-tabs">
        <li ng-repeat="tab in tabs" ng-class="{'active': tab.isActive }" ng-click="tabClick($index);">{{tab.text}} {{ params.device_name }}s</li>
</ul>

the second one is the actual angular way just started with the first one for a easy transition. 第二种方法是从第一种方法开始的实际角度方法,以便轻松过渡。

Hope helps. 希望会有所帮助。

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

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