Switch between 2 buttons by using ng-class in Angular JS

In a button group, one button is designated as "active" by the ng-class attribute (either myCtrl.onactive or myCtrl.offactive)

<div class="btn-group pull-right">
        <button ng-class="{active: myCtrl.onactive}" class="btn" ng-click="myCtrl.changeColorIcons()">on</button>
        <button ng-class="{active: myCtrl.offactive}" class="btn" ng-click="myCtrl.changeColorIcons()">off</button>
</div>

The goal is to have only the clicked button display the active class

Currently attempting this in the controller with the following code:

self.onactive = true; //by default, the "on" button is active

//switch active state when a button is clicked
this.changeColorIcons = function() {
    if (self.onactive) {
        self.offactive = true;
        self.onactive = false;
    } else {
        self.onactive = true;
        self.offactive = false;
    }
};

Answer №1

Check out this code snippet that is ready to use. Simply copy and paste the following function into your JavaScript:

var app = angular.module("app", []);
app.controller("Ctrl", ["$scope",
  function($scope) {

    var myCtrl = this;
    myCtrl.onactive = true;
    myCtrl.offactive = false;

  myCtrl.changeColorIcons = function(button) {

      if (button === 'on') {
        myCtrl.onactive = true;
        myCtrl.offactive = false;
      } else if ( button === 'off') {
        myCtrl.onactive = false;
        myCtrl.offactive = true;
      }
    };
  }
]);
.active {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="Ctrl as myCtrl" class="btn-group pull-right">
    <button ng-class="{active: myCtrl.onactive}" class="btn" ng-click="myCtrl.changeColorIcons('on')">on</button>
    <button ng-class="{active: myCtrl.offactive}" class="btn" ng-click="myCtrl.changeColorIcons('off')">off</button>
  </div>
</div>

Answer №2

In my opinion, solving this issue can be done simply by changing the HTML code without the necessity of creating a new function in the controller. Feel free to have a look at this demo I've prepared for you: http://jsfiddle.net/Lvc0u55v/11094/

Alternatively, you can replace your existing HTML code with the following:

<div class="btn-group pull-right">
<button ng-class="onactive" class="btn" ng-click="onactive='active'; offactive='inactive';">on</button>
<button ng-class="offactive" class="btn" ng-click="offactive='active';onactive='inactive'">off</button>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Master the art of sending multiple asynchronous requests simultaneously with suspense in Vue 3

Utilizing <Suspense>, I am handling multiple requests in my child component using the await keyword: await store.dispatch("product/getProduct", route.params.id).then(res => productData.value = res); await store.dispatch("product/get ...

Accessing attribute value of selected option in AngularJS select element

I have a select tag that displays options, and I want it so that when an option is selected, the value of the data-something attribute is copied into the input element. This is just for demonstration purposes; the actual value should be sent in the form. ...

Suggestions for relocating this function call from my HTML code

I have been working on updating a javascript function that currently uses an inline event handler to a more modern approach. My goal is to eliminate the unattractive event handler from the actual HTML code and instead place it in a separate modular javascr ...

Can anyone provide guidance on how to simulate a click on a JavaScript action for an iPhone?

I am attempting to trigger a click on a "javascript:void(0)" link so that I can retrieve HTML data within the script. Can someone advise me on how to achieve this without using illegal APIs like UITouchEvent, as I only work with NSUrl? Thank you in advan ...

user input not displayed within md-autocomplete

I'm currently incorporating angular material's autocomplete component into my website. Within the html code, I have the following: <md-autocomplete md-selected-item="selectedItem" md-search-text="searchText" md-items="item in getMatches ...

Getting the value or index of an inputbox in AngularJS

Angularjs <tr ng-repeat="advLi in media"> <td> <input style="display:none;" type="text" style="width:35px;" class="form-control" name="mediaindex" value="{{$index+1}}" ng-model="advLi.media_order"> </td> <td& ...

What could be causing my Puppeteer scraper to malfunction when I alter the search term?

The Task In this project, I am building a web scraper using NodeJS with Puppeteer. The goal is to scrape data for "Jeep Wranglers" and organize the results in JSON format. Comparing IPhone X and Jeep Wrangler Initially, everything worked smooth ...

Error in material mapping: glDrawElements is trying to access vertices that are out of range in attribute 2

I have developed an algorithm that allows users to input data or a function and then generates a graphical representation of the function. It essentially creates a surface map, similar to the one you can see here. The graphing functionality is working well ...

What is the best way to retrieve past data using RTK Query?

When working with data retrieval using a hook, my approach is as follows: const { data, isLoading } = useGetSomeDataQuery() The retrieved data is an array of items that each have their own unique id. To ensure the most up-to-date information, I implement ...

Changing the background color of the dropdown button in Vue Bootstrap: A step-by-step guide

I've been struggling to modify the background color of a dropdown button, but no method seems to work. I've attempted changing it by using ID, removing its class and applying a new one, and even using !important to override the styles, but the ba ...

Error: react/js encountered an unexpected token

While attempting to execute my project, I encountered an error in the console related to a function within the code. The exact error message reads as follows: "63:25 error Parsing error: Unexpected token, expected (function toggleDrawer = (open) => () ...

What is the best method for sending data from Node.js Express to Ember-Ajax?

I am currently developing a website using Ember with a Node JS Express API, and I am utilizing ember-ajax to communicate with the API. EDIT: Ember version: 1.13 Ember Data: 1.13.15 The issue I am facing is that when Ember makes an AJAX call, it seems t ...

A step-by-step guide on enabling Autoclick for every button on a webpage

I am currently using Jquery and Ajax to carry out an action, my goal is for a code to automatically click on every button once the page has finished loading. Although I attempted to use the following javascript code to achieve this at the end of my page, ...

Transform json nested data into an array using JavaScript

Can anyone assist me in converting Json data to a Javascript array that can be accessed using array[0][0]? [ { "Login": "test1", "Nom": "test1", "Prenom": "test1p", "password": "124564", "Email": "<a href="/c ...

Side-by-side arrangement of AngularJS Accordion in a vertical layout

I am looking to change the layout of the accordions from being stacked on top of each other to being displayed side by side. I have attempted to add a span above the accordion-group but it did not provide the desired effect. <div id="top-panel" style=" ...

I am unable to retrieve information from Firebase in Vue

Currently, I am following a tutorial on YouTube to enhance my knowledge about storing data in Firebase and then utilizing it in a Vue application. (You can watch the tutorial at this link: https://www.youtube.com/watch?v=Htt8AKeF1Kw, you will encounter the ...

Tips for positioning two elements side by side on a small screen using the Bootstrap framework

Greetings! As a beginner, I must apologize for the lack of finesse in my code. Currently, I am facing an issue with the positioning of my name (Tristen Roth) and the navbar-toggler-icon on xs viewports. They are appearing on separate lines vertically, lea ...

Organize a collection of objects into a fresh array

I am facing an issue where I have an array and I need to transform it into an array of its children elements. var data = [{ name: 'Cars', content: 'BMW', value: 2000 }, ...

Error: VueJS mixins do not include the property definition

I've been trying to incorporate Mixins into my Vue.js code, but I've run into a few issues :/ Here's the current code for two test modules : ErrorBaseMixin.vue <script> import ErrorAlert from './ErrorAlert'; expor ...

Error not caught: AngularJS module error

Initially, I was hesitant to ask this question, but after struggling for two hours without any success, I've decided to seek some assistance. I'm trying to integrate the ngResource module into my application. Prior to this, everything was functi ...