Toggle the selection of a div by clicking a button in AngularJS with a toggle function

I have several div elements on a webpage.

Each div contains a button!

  • When the button is clicked for the first time:
    • The border color of the div will change to blue (indicating the div is now selected).
    • The "ok" button will be hidden (leaving only the selected div visible).
  • Clicking anywhere inside the div for the second time will deselect it:

    • The border will return to its original black color.
    • The button will become visible again.
  • By clicking the select all button for the first time, the div should be selected. Clicking it again will unselect the div. (Toggle action)

How can I achieve this functionality using AngularJS.

fiddle

function MainCtrl($scope) {
   $scope.addBackground = function () {
       angular.element(document.querySelector('.container')).addClass('selectedBorder');
      angular.element(document.getElementById('okBtn')).css('display','none');
    };
};
.container{
  width:30%;
  height:100px;
  border:1px solid black;
  margin:10%;
}
button.btn.btn-primary{
  margin-top:10%;
  margin-left: 40%;
}
.selectedBorder{
  border: 3px solid blue;
}
<div id="myAngularApp" title="Angular Scope" ng-app ng-controller="MainCtrl">
   
<div class="container">
<button id="okBtn" class="btn btn-primary" ng-click="addBackground()">ok</button> 
</div>
</div>

Answer №1

To implement this functionality in AngularJs, you need to utilize ng-class and ng-show:

<div class="container" ng-class="{ 'selectedBorder': containerSelected }" ng-click="toggleContainer()">
    <button id="okBtn" class="btn btn-primary" ng-click="toggleButton($event)" ng-show="buttonVisible">ok</button> 
</div>

function MainCtrl($scope) {

   $scope.containerSelected = false;
   $scope.buttonVisible = true;
   $scope.toggleButton = function (e) {
       $scope.containerSelected = true;
       $scope.buttonVisible = false;
       e.stopPropagation();
    };
    $scope.toggleContainer = function (e) {
       if($scope.containerSelected){
           $scope.containerSelected = false;
           $scope.buttonVisible = true;
       }
    };

};

Check out the live demo: demo

Answer №2

To prevent event propagation, you can use $event.stopPropagation(); when triggering another event on the click of a box.

function MainCtrl($scope) {
   $scope.addBackground = function () {
       angular.element(document.querySelector('.container')).addClass('selectedBorder');
      angular.element(document.getElementById('okBtn')).css('display','none');
    };
    
    $scope.removeBackground = function () {
       angular.element(document.querySelector('.container')).removeClass('selectedBorder');
      angular.element(document.getElementById('okBtn')).css('display','initial');
    };
};
.container{
  width:30%;
  height:100px;
  border:1px solid black;
  margin:10%;
}
button.btn.btn-primary{
  margin-top:10%;
  margin-left: 40%;
}
.selectedBorder{
  border: 3px solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.3/angular.min.js"></script>

<div id="myAngularApp" title="Angular Scope" ng-app ng-controller="MainCtrl" ng-click="removeBackground()">
   
<div class="container">
<button id="okBtn" class="btn btn-primary" ng-click="addBackground(); $event.stopPropagation();">ok</button> 
</div>
</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

Remembering data in a lazy loaded AngularJs list

Encountering an issue with a lazy loaded list of books. Initially, 10 books are loaded and if the user scrolls down, the next 10 books are loaded. For example, if the user is on "page" 4 and clicks on the 35th book to view details, upon returning to the l ...

Enhancing a validation form with the 'onblur' event handler

Exploring the realm of JavaScript, I find myself intrigued by the concept of creating a validation form that activates upon clicking out of the input field. Implementing various techniques to integrate this feature into an existing form has been both chall ...

What is preventing me from getting jQuery UI 1.8.20 dialog to function on JSFiddle?

My attempt to implement jQuery UI dialog in JSFiddle has been unsuccessful, consistently resulting in a dialog opening error caused by a deep-seated issue within jQuery UI: Uncaught TypeError: Cannot read property '3' of undefined. Although I am ...

What is the best way to utilize Typescript when making queries to Firebase?

I have successfully integrated push notifications for my app using Firebase Cloud Functions. Now, I am looking to enhance the user experience by updating the app's badge count alongside the push notifications. I understand that this can only be achiev ...

The JavaScript for loop using .appendChild() is inserting the values of the final object, represented as [object object], into the HTML document

$(document).ready(function () { GetDetails(); }); function GetDetails() { let albumlist = document.getElementById("album-list"); $.ajax({ url: '/Store/browseajax', type: 'GET', data: { id: '@ ...

Creating a mapping in Node.js to write to a serial port and then retrieve the

Currently, I am utilizing the node-serialport module for serial port communication. My goal is to send the command ATEC and receive a response of ECHO. However, the process of sending and receiving data is asynchronous (after sending the data, the timing ...

The default export (imported as 'Vue') could not be located within the 'vue' module in Vue 3 and Laravel

I'm currently in the process of building a project that combines Laravel 8 and Vue JS 3. I've set everything up, but whenever I try running `npm run watch`, I encounter an error message similar to the one below. Despite looking through various fo ...

Is there a way to directly display all the content in pagination format without a print preview option?

I have been tasked with implementing a feature that involves displaying content using pagination and allowing users to print all the content at once with a single click on a print button. However, I am currently experiencing an issue where clicking the pri ...

I am seeing the number 1 mysteriously popping up on my HTML page without my intervention

Working on a website design, I encountered an issue with my HTML code. When executing and displaying content from a PHP file on the page, a strange number 1 is added after parsing the PHP file's content. Here is the snippet of HTML and PHP causing th ...

Is there a way to utilize variables from a source XML file to establish points on an SVG polygon?

I've been struggling to figure out if it's possible to dynamically set points on an SVG polygon using variables that are defined by an XML document which is constantly changing. All I want is to set the path like this: var polygonToUse = window. ...

Using a UUID as the default ID in a Postgres database system is a straightforward process

As I transition to postgres from mongodb due to the recent announcement, I've noticed that the IDs are simply numerical and auto-incremented. I've attempted a few solutions: Setting the default ID to a UUID with a lifecycle hook - Unfortunately, ...

When using React, I noticed that adding a new product causes its attributes to change after adding another product with different attributes on the same page

Imagine you are browsing the product page for a Nike T-shirt. You select black color and size S, adding it to your cart. The cart now shows 1 Nike T-SHIRT with attributes color: black, size: S. However, if you then switch to white color and size M on the ...

How to convert table headings in Bootstrap-Vue.js

For a few nights now, I've been struggling to translate the table header in my vue.js component. It seems like I'm missing something as I'm new to Vue.js and can't seem to figure out what's wrong. Translating within the HTML works ...

"Improvements required for the search and filter functionality in the JSON

My JSON function retrieves image data and displays it in panels. Here is an example of the code: $.getJSON('iproducts.json',function(products){ var output = ""; $.each(products.appleitems, function(i, product) { output += "<di ...

Role-based dynamic layout

I am currently working on a website that requires user login functionality. To achieve this, I am utilizing materialise-css and Angularjs for the front-end development, while the back-end is powered by Java-Hibernate (as Spring is not an option in my case) ...

Utilizing Skeleton to create a cropped text button on an iPhone

I am currently using Skeleton for my simple CSS needs. While it works fine on desktop, I have noticed that on an iPhone, the text in my button gets cropped as shown in the picture. https://i.stack.imgur.com/EYo2P.png Below is the HTML code I'm using ...

When the dialog is opened, automatically set the focus on the text field inside

I am facing an issue with focusing a custom text field when opening a dialog. I have tried using vue.js refs: Code: <v-app id="app"> <v-row align="center"> <v-col class="text-center" cols="12"> <v-btn color="primary" @cli ...

React Form with Conditional Input Options and Validation

Just diving into the world of React, I find myself connecting a React frontend to a Flask backend in a group project. Surprisingly, I've ended up handling about 90% of the workload. While I have utilized MUI for implementing fields, my focus is more o ...

Executing numerous xhttp.send requests within a single webpage

Hey there, I'm facing an issue with xhttp.send(); as it keeps giving me the error message net::ERR_EMPTY_RESPONSE Here is a snippet of my code. Whenever a user clicks too quickly, they get kicked off the page. Is there a way to prevent this? docum ...

H3 Element Without ASP Causing Disruption in Page Layout

Looking at my .aspx page, I have the following code: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <link href="BootStrap.css" rel="stylesheet" type="text/css" /&g ...