AngularJS button toggling show/hide functionality

Trying to achieve: A button that toggles the visibility of a div based on the checkbox state in an ng-repeat directive. Plunker

  <button ng-click="toggleIt()">Toggle it</button>
  <p>Check all</p>
  <input type="checkbox" ng-model="selectAll" ng-click="checkAll()" />
  <br />
  <p>Checkboxes</p>
  <input type="checkbox" ng-repeat="c in checkbox" ng-model="checkbox[$index].selected">
  <div ng-show="checkbox[0].selected && shownow">Slave one showed!</div>
  <div ng-show="checkbox[1].selected && shownow">Slave two showed!</div>
  <div ng-show="checkbox[2].selected && shownow">Slave three showed!</div>

app.controller('MainCtrl', function($scope) {
  $scope.checkbox = [{
    selected: false
  }, {
    selected: false
  }, {
    selected: false
  }];
  // Check/uncheck all boxes
  $scope.checkAll = function() {
    angular.forEach($scope.checkbox, function(obj) {
      obj.selected = $scope.selectAll;
      $scope.shownow = false;
    });
  };

  $scope.shownow = false;


  $scope.toggleIt = function() {
    $scope.shownow = true;
  }

  $scope.$watchGroup(['checkbox[0].selected', 'checkbox[1].selected', 'checkbox[2].selected'], function(newValue, oldValue) {
    if (newValue != oldValue) {
      $scope.shownow = false;
    }
  });
});

Issue at hand: When unchecking one of the checkboxes, the associated div disappears when it's not supposed to...

Answer №1

Try this:

JavaScript File

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

app.controller('MainCtrl', function($scope) {
  $scope.checkbox = [
    {
      selected: false
    },
    {
      selected: false
    },
    {
      selected: false
    }
  ];
  
  $scope.checkAll = function () {
    angular.forEach($scope.checkbox, function (obj) {
      obj.selected = $scope.selectAll;
       $scope.shownow = true;
    });
  };

  $scope.toggleIt = function(){
    $scope.shownow = !$scope.shownow;
    $scope.selectAll = ! $scope.selectAll
    $scope.checkAll();
  }

});

HTML File

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Project</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e3c323b29303223363f2322523d373d0b">[email protected]</a>" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">


  <button ng-click="toggleIt()">Toggle it</button>
  <p>Select All</p>
  <input type="checkbox" ng-model="selectAll" ng-click="checkAll()" />
  <br />

  <p>Checkboxes</p>
  <input type="checkbox" ng-repeat="c in checkbox" ng-model="checkbox[$index].selected">


  <div ng-show="checkbox[0].selected && shownow">Slave one displayed!</div>
  <div ng-show="checkbox[1].selected && shownow">Slave two displayed!</div>
  <div ng-show="checkbox[2].selected && shownow">Slave three displayed!</div>
</body>
</html>

Please check out the modified fiddle: "http://plnkr.co/edit/7GXqApEjfPkZFsQeLbQM?p=preview"

Answer №2

Instead of embracing the solution you created by watching for checkbox changes and hiding divs accordingly, you are now questioning whether this approach is correct...

$scope.$watchGroup(['checkbox[0].selected', 'checkbox[1].selected', 'checkbox[2].selected'], function(newValue, oldValue) {
    if (newValue != oldValue) {
      $scope.shownow = false;
    }
});

Will eliminating this code section give you the desired outcome?

Answer №3

Make sure to incorporate || when updating it

<div ng-show="checkbox[0].selected || shownow">Presenting: Slave one!</div>
<div ng-show="checkbox[1].selected || shownow">Introducing: Slave two!</div>
<div ng-show="checkbox[2].selected || shownow">Behold: Slave three!</div>

Your plunker has been revised. Please review it here

Answer №4

Could you please modify the method like this:

$scope.toggleIt = function(){
    $scope.shownow = !$scope.shownow;
  }

Furthermore, there is no need to include the watcher.

This approach should work well. You can check out the plnkr for reference.

UPDATED PLNKR :

http://plnkr.co/edit/WN9ohx?p=preview

Answer №5

Based on the specific requirements mentioned in the original post's comments:

In Angular, model binding updates in real-time, meaning that changes are reflected immediately when interacting with elements like checkboxes. However, if you need to delay the update until a button click, you can achieve this by storing the displayed results in another variable and updating them only when necessary.

$scope.showDivs = $scope.checkbox.map(function(item){
  return item.selected;
});

<div ng-show="showDivs[0]">Slave one is visible!</div>
<div ng-show="showDivs[1]">Slave two is visible!</div>
<div ng-show="showDivs[2]">Slave three is visible!</div>

Check out the working example on Plunker

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

Tips for Preventing Unnecessary Ajax Requests

What I require When a click event is triggered, a service call should be made only once. Use case Dropdown1 Dropdown2 Dropdown3 1. There are three dropdowns on the HTML page. 2. When Dropdown1 is called - an AJAX call is made only onc ...

Looking for real-life applications of "callThrough" and "callFake()" in Jasmine?

Currently, I am in the process of mastering the implementation of karma and Jasmine in AngularJS. To enhance my understanding, I have been studying various examples. I find myself a little puzzled by the concept of callThrough. If my understanding is inc ...

Ensure that there are three unique JS code blocks in a single JS file, and avoid repetition of any block if it appears more than three times on

In my HTML page, I have 3 distinct blocks of code named block-1, block-2, and block-3 located in the file script.js. This script is called three separate times within the same page. I want to ensure that each block is executed only once based on the order ...

Is it possible for the await block to be located outside of the async function that contains it?

setInterval(() => { // perform certain actions }, 1000) const bar = async () => { const response = await api_request(); do_actions(); } await bar(); When the foo function is set to run, will it interfere with the execution of the setInterval ...

Developing a unique JavaScript object by extracting information from a jQuery AJAX response

Is there a recommended approach for creating a custom JavaScript object that contains data retrieved from a jQuery AJAX request? I'm considering two methods, but unsure which is the most appropriate. The first method involves including the AJAX reques ...

The alert function in the Ajax web method is malfunctioning

Every time I try to call the Ajax web method, I keep receiving a 'save error' message. However, the data is successfully saved to the database without any issues. I have checked for errors but couldn't find any. How can I display an alert sa ...

What is the process for adjusting the size of a gridHelper in three.js?

import * as THREE from '/build/three.module.js'; let scene, camera, renderer, gridHelper; scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000); camera.position.set(0, 150 ...

What are some potential causes of webpack-dev-server's hot reload feature not working properly?

Having an issue with my React project. When I try to use hot reload by running "npm start" or "yarn start" with webpack-dev-server configured (--hot flag), I'm getting the error message: [error message here]. Can anyone assist me in troubleshooting th ...

How can you combine multiple arrays of nested objects in ES6?

Here is an example array I have: [ { data: [ { a: "a", b: "b" }, { x: "x", y: "y" }, ], }, { data: [ { c: "c", d: "d" }, { z: "z", f: "f&qu ...

Error encountered while attempting to send SendGrid email to multiple recipients

Currently, I am using const sgMail = require('@sendgrid/mail'); with sendgrid version 7.6.2. Whenever I attempt to add two email addresses in an array and then pass it into either send() or sendMultiple(), an error is being thrown like below. st ...

The message "The data format for the chart type is incorrect" pops up every time I try to input an array for a line graph

I am attempting to dynamically send array data to draw a chart. My goal is to receive input values [x and y] from the user using HTML. I have been successful in retrieving the data from HTML, but when I pass it to the chart, the format is not being recog ...

The ASP.NET MVC3 form collection registers as 0 when performing a jQuery ajax post

I'm currently developing a project on ASP.NET MVC3. My current challenge involves POSTing to a method that should return a set of data using the jQuery.ajax api. However, upon handling the request on the server, I noticed that the form collection&apo ...

Issue with the positioning of bootstrap popover after content is added

Having trouble writing a function that adds a textarea to the bottom of a popover content when clicking on a button. The issue is that once the textarea is displayed, the popover extends downward and obscures the text. I'm looking for a solution where ...

The functionality of Javascript stops working once an ajax call is made

My attempt to make an Ajax call to fetch additional data upon clicking a button was successful on the first click. However, subsequent clicks on the button do not trigger the action, and the data retrieved does not apply any JavaScript functionalities like ...

When a dropdown is clicked, it will close any other dropdowns that are currently

Upon clicking on the top menu link "menu item 01", the 3 level drop down opens as expected. Similarly, when you click on "menu item 04", the mega menu expands perfectly. However, I am looking to achieve a functionality where if the user clicks on any othe ...

Run each test individually, ensuring compatibility across all browsers

Currently, I am creating my E2E tests using testcafe with a test backend that does not have support for concurrency. This means that if two tests are running in parallel, the test backend crashes. When I run tests against a single browser, they are execut ...

Referencing an object by using a variable containing its name

I need a way to reference an object using a variable with its name in it. I've figured out how to do this for properties and sub-properties: var req = {body: {jobID: 12}}; console.log(req.body.jobID); //12 var subProperty = "jobID"; cons ...

Obtain a random item from an array containing elements with assigned weights

In my game development project, I have an array of objects representing creatures. Each creature object includes a unique identifier and a corresponding weight or probability for spawning. I am struggling to create an algorithm that will randomly spawn cr ...

Host image previews on the server using Dropzone.js

I'm currently utilizing Dropzone.js along with Angular.js for image uploads. However, I haven't been able to figure out a way to upload thumbnails to my server. .dropzone({ url: "/gallery/add", maxFilesize: 100, paramName: "up ...

The NW JS window loaded event fails to trigger when loading a URL, but functions properly when loading from a local

Having trouble triggering the loaded event on a live webpage compared to a local page. The loaded event fails to fire with this code: var mywin = nw.Window.open('http://www.google.com', {"frame": false}, function(testWin) { testWin.on(&apos ...