How to disable a button in AngularJS when all variables in an object are set to false

I need to implement a feature where only one button can be selected at a time from a list of buttons. When no button is selected, I want to disable another button elsewhere on the page.

Below is the code snippet for the buttons:

<button type="button" ng-repeat="service in services_data track by service.id" ng-class="showDetails[service.id] ? 'bg-success': 'bg-default'" ng-init="selected[service.id] = false" ng-click="showDetails[service.id] = showDetails[service.id]; select_check(showDetails)" class="list-group-item item_buttons">
  <ul class="list-unstyled">
     <li>{{service.name}} - {{service.est_time_mins}} mins. | ${{service.price}}</li>
     <li>{{service.style}}</li>
  </ul>
</button>

A click on any button toggles the "showDetails" variable, setting it to TRUE if the button is selected and FALSE if deselected.

I am trying to write a function that checks the status of all buttons to determine when to disable a specific button. However, my attempts with loops and conditional statements have not been successful so far.

Answer №1

Here is a code snippet that I wrote to assist you:

Link to the code

HTML:

<div ng-controller="MyCtrl">
<button type="button" ng-repeat="service in servicesData" ng-class="{'bg-success': service.selected, 'bg-default': !service.selected}" ng-click="service.selected = !service.selected" class="list-group-item item_buttons">
  <ul class="list-unstyled">
     <li>{{service.name}} - {{service.est_time_mins}} mins. | ${{service.price}}</li>
     <li>{{service.style}}</li>
  </ul>
</button>

<br>
<button class="another-button" ng-disabled="disableAnotherButton">ANOTHER BUTTON!</button>

JS:

var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {

        $scope.disableAnotherButton = false;

    $scope.servicesData = [
        {
        id: 1,
        name: 'Button A',
        price: 1000,
            selected: false
        },{
        id: 2,
        name: 'Button B',
        price: 2000,
            selected: false
        }
   ];

   $scope.$watch('servicesData', function(newServicesData){
      $scope.disableAnotherButton = newServicesData.every(elem => elem.selected == true); 
   }, true);

}

(UPDATE)

You can also manage the logic in a separate array.

Updated link for the code

(UPDATE 2)

This version does not use ECMAScript 2015 syntax.

Alternative version of the code

Answer №2

Give this a try ... Insert the following function into your script. It will expand the capabilities of the JavaScript Array Prototype

Array.prototype.all = function (fn) {
   var b = true;
   var arr = this;
   fn = fn || function (i) {return true};
   arr.forEach(function (item) {
       if (fn(item) == false) b = false; 
   });
   return b;
}

Then, use this code to disable a specific button depending on the condition

<button class="other-button" ng-disabled="services_data.all((service) => showDetails[service.id])">OTHER BUTTON</button>
<!--If your browser supports ECMA SCRIPT 6, I suppose

Alternatively...

<button class="other-button" ng-disabled="services_data.all(function (service) { return showDetails[service.id] })">OTHER BUTTON</button>
<!--If your browser doesn't support ECMA SCRIPT 6

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

Unable to fulfill all the promises in JavaScript

As I develop a filter feature, I have categories and cities in the format: ['New York'], ['Cars']. The goal is to iterate through them to retrieve products based on each city or category. My approach involves storing these products in t ...

What is the process for submitting and storing a collection of files in a database as a list?

I am trying to implement a feature in my MVC project where users can upload multiple files and see them listed before submitting the form. However, I am facing some challenges with finding a solution for this. Demo: My goal is to allow users to add multi ...

get data from a JSON array with no specific name on the provided URL

Struggling to extract specific values from a JSON file located at the following URL: The content of the URL data is as follows: [ { "key":{ "parentKey":{ "kind":"user", "id":0, "name":"test 1" }, ...

Why is Jquery's .addClass and .removeClass not functioning as expected?

Recently, I implemented a feature in my code where clicking on an item would display a contextual menu (in the form of a div) that allows users to cut and paste list items. To control the functionality, I added a 'disabled' class to the buttons w ...

Issue at hand: Unexpected error 500 encountered while sending AJAX request to PHP script through

UPDATE: Issue Resolved! I want to extend my gratitude to everyone who directed me to the error log files for assistance. The community here is truly incredible and I was able to get a resolution much quicker than anticipated. It's quite embarrassing, ...

"Can you send multiple variables using an Ajax post by using a loop

I'm trying to figure out how to post multiple variables from dynamically generated "username" ids like "username1", "username2", and so on, all in one ajax post request. The issue I'm facing is mainly with the data parameter. var numOfInputs = $ ...

What is the correct way to employ async/await in combination with Array.filter within a React application?

I'm currently in the process of developing a basic currency converter using React and Typescript. Below is a snippet of my component code: const App = () => { const [countries, setCountries] = useState<Array<CountriesProps>>([]) co ...

Contrast objects and incorporate elements that are different

In my scenario, I have a list of days where employees are scheduled to work. However, on the website, I need to display the remaining days as leave. In cases where an employee has two different shifts, there can be two elements in the object. var WorkDays ...

The use of refs on Function components in SVG is not supported. Any attempts to access the ref will result in an

I am currently working on integrating a navigation bar component using an SVG image in Next.js. While attempting to import and utilize the SVG image, I encountered an error that I couldn't resolve. I tried using Emotion JS to create and use the SVG, ...

Exploring the process of implementing a dynamic background image feature in Vue

Looking to create a dynamic navbar and change its background image. I attempted the following: Here is my attempt: <b-navbar toggleable="lg" v-bind:style="headerStyle"> this.headerStyle = { backgroundImage: &a ...

Pulling a div from beneath numerous other divs

I have been attempting to create a test case for a web application we are developing and I am on the verge of finding a solution, but there is one final hurdle that has me puzzled... Our requirement is to enable div elements to be draggable (which is work ...

Unable to process despite clicking button (no error messages)

I'm in the process of setting up an options page for my very first extension. As a beginner in coding, I might have made some rookie mistakes along the way. However, I am facing challenges with basic functionality that was previously working seamlessl ...

disable input box stationary

Is there a way to make a checkbox stay disabled even after refreshing the page? Currently, when I click the checkbox it disables, but upon refreshing the page, it goes back to being enabled. $( "input[type='checkbox']").click(function(event){ ...

Guide on changing templates based on parameters in $stateParams using ui-router

Currently, I am in the process of developing an application using AngularJS and ui-router. The structure I have set up involves nested states as shown below: .state('ls.resource', { url : '/:resource', abstract: true, template: " ...

Utilizing commands in conjunction with phonegap

Currently, I am utilizing yeoman to create an Angular application and then deploying it using phonegap onto a mobile platform - specifically iOS. However, I have encountered some difficulties in getting directives to function properly. One of the directiv ...

The GetJSON function is designed to fetch the entire array of data, without selectively retrieving specific

Below is the implementation of my GetJSON method: $(document).ready(function () { $.getJSON("/user", function (obj) { $.each(obj, function (key, value) { $("#usernames").append(value.firstname); console.log(ob ...

Warning: Neglecting to handle promise rejections is now considered outdated and discouraged

I encountered this issue with my code and I'm unsure how to resolve it. DeprecationWarning: Unhandled promise rejections are deprecated. In the future, unhandled promise rejections will terminate the Node.js process with a non-zero exit code. This ...

The data received by request.responseText is accurate, however JavaScript is unable to interpret it

I am currently diving into the world of AJAX and educating myself using Head First AJAX. I have encountered a strange issue while working on a simple program that makes a request using JavaScript and displays the output. main.js window.onload = initPage; ...

how to set a boolean value to true in a vue @click event?

@click.native="scrollTo(index,true)" My expectation: Always pass Boolean:true into the scrollTo function. Vue's reaction: Vue interprets true as a variable name, resulting in Number:index and undefined instead. Solution: ...

What is causing this error/bug to show up in Angular?

I encountered an error while working on my Angular project that incorporates both front-end and back-end development with Python Flask. Even though the page updates correctly, a database-related error is being displayed in the console. Below are the snippe ...