简体   繁体   中英

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 . In addition to this though I want the buttons to be clickable and onclick, the clicked tab has the active class. 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?

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;

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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