Press on a specific div to automatically close another div nearby

var app = angular.module('app', []);
app.controller('RedCtrl', function($scope) { 
  $scope.OpenRed = function() {
    $scope.userRed = !$scope.userRed;
  }
  $scope.HideRed = function() {
    $scope.userRed = false;
   }  
});
app.directive('hideRed', function($document) {
  return {
    restrict: 'A',
    link: function(scope, elem, attr, ctrl) {
      elem.bind('click', function(e) {
        e.stopPropagation();
       })
      $document.bind('click', function() {
       scope.$apply(attr.hideRed);
      })
    }
   }
});

app.controller('BlueCtrl', function($scope) { 
  $scope.OpenBlue = function() {
    $scope.userBlue = !$scope.userBlue;
  };
  $scope.HideBlue = function() {
    $scope.userBlue = false;
  };  
});
app.directive('hideBlue', function($document) {
  return {
    restrict: 'A',
    link: function(scope, elem, attr, ctrl) {
      elem.bind('click', function(e) {
      e.stopPropagation();
    });
       $document.bind('click', function() {
        scope.$apply(attr.hideBlue);
     })
    }
  }
});
body {
  position: relative;
   display:flex;
}
a
{
margin-right:20px;
}
.loginBox 
{
  z-index: 10;
  background: red;
  width: 100px;
  height: 80px;
  position: absolute;
}

.fontSize 
{
  font-size: 30px;
}
.loginBoxBlue
{
  z-index: 10;
  background: blue;
  width: 100px;
  height: 80px;
  position: absolute;
  display:flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="app">
  <body>
    <div ng-controller="RedCtrl">
      <a href="#" ng-click="OpenRed()" hide-red="HideRed()"  ng-class="{'fontSize': userRed}">Show Red</a>
      <div hide-red="HideRed()" class="loginBox" ng-show="userRed"></div>
    </div>
    <div ng-controller="BlueCtrl">
      <a href="#" ng-click="OpenBlue()" hide-blue="HideBlue()"  ng-class="{'fontSize': userBlue}">Show Blue</a>
      <div hide-blue="HideBlue()" class="loginBoxBlue" ng-show="userBlue"></div>
    </div>
  </body>
</html>

Hey there! By clicking on Show Red or Show Blue, you can show red and blue boxes respectively. These boxes can be closed by clicking outside of them or clicking on the text again. If both texts are clicked, both divs will be shown.

Now, the question is, how can we make it so that when you click on Show Red, the blue box is hidden and vice versa? Essentially, we want only one box to be visible at a time.

Answer №1

Is there a specific reason for implementing two controllers in your code? It seems to add unnecessary complexity to your app. Consider using just one controller, such as RedCtrl, to simplify communication between variables.

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

app.controller('RedCtrl', function($scope) {
  $scope.OpenRed = function() {
    $scope.userRed = !$scope.userRed;
    $scope.userBlue = false;
  }
  $scope.HideRed = function() {
    $scope.userRed = false;
  }
  $scope.OpenBlue = function() {
    $scope.userBlue = !$scope.userBlue;
    $scope.userRed = false;
  };
  $scope.HideBlue = function() {
    $scope.userBlue = false;
  };
});

app.directive('hideRed', function($document) {
  return {
    restrict: 'A',
    link: function(scope, elem, attr, ctrl) {
      elem.bind('click', function(e) {
        e.stopPropagation();
      })
      $document.bind('click', function() {
        scope.$apply(attr.hideRed);
      })
    }
  }
});

app.directive('hideBlue', function($document) {
  return {
    restrict: 'A',
    link: function(scope, elem, attr, ctrl) {
      elem.bind('click', function(e) {
        e.stopPropagation();
      });
      $document.bind('click', function() {
        scope.$apply(attr.hideBlue);
      })
    }
  }
});
body {
  position: relative;
  display: flex;
}

a {
  margin-right: 20px;
}

.loginBox {
  z-index: 10;
  background: red;
  width: 100px;
  height: 80px;
  position: absolute;
}

.fontSize {
  font-size: 30px;
}

.loginBoxBlue {
  z-index: 10;
  background: blue;
  width: 100px;
  height: 80px;
  position: absolute;
  display: flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="app">

<body ng-controller="RedCtrl">
  <div>
    <a href="#" ng-click="OpenRed()" hide-red="HideRed()" ng-class="{'fontSize': userRed}">Show Red</a>
    <div hide-red="HideRed()" class="loginBox" ng-show="userRed"></div>
  </div>
  <div>
    <a href="#" ng-click="OpenBlue()" hide-blue="HideBlue()" ng-class="{'fontSize': userBlue}">Show Blue</a>
    <div hide-blue="HideBlue()" class="loginBoxBlue" ng-show="userBlue"></div>
  </div>
</body>

</html>

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

Error encountered while rendering ngMessages error in AngularJS due to ngif markup issue

I am currently utilizing ngMessages to validate a dynamically generated form using ngRepeat. While ngMessages is functioning as expected, I want the validation error messages to only display when the submit button is clicked. To accomplish this, I am emplo ...

The local server for running AngularJS with npm start is experiencing technical difficulties and is

As a newcomer to AngularJS, I recently embarked on creating a sample project which involved setting up a basic template store using Angular seed. Initially, I encountered some challenges with installing bower components. However, after conducting extensive ...

Retrieve data from Last.fm API by utilizing both Node.js and Angular framework

I am currently working on implementing the node-lastfmapi track.search method into my project. I have successfully retrieved the results, but I am facing challenges in integrating them into the front end using Angular. My backend is powered by mongoDB and ...

Exploring the Integration of AngularJS with MVC Subdomains

We are looking to incorporate some AngularJS SPA features into our existing MVC 5 application. To achieve this, we have created a new MVC Area within the application and set up a default controller called HomeController. namespace Acme.WebAdmin.Areas.Sche ...

Step-by-step guide on inserting a div element or hotspot within a 360 panorama image using three.js

As I work on creating a virtual tour using 360 images, I am looking to include hotspots or div elements within the image that can be clicked. How can I store data in my database from the event values such as angle value, event.clientX, and event.clientY wh ...

Is it feasible to maintain a variable as a reference across views while utilizing ng-view?

I am facing a unique challenge: I have a webpage with two tabs that need to utilize ng-view from AngularJS. The twist is that both tabs must share the same variable, similar to referencing a variable in C# using the "ref" keyword. If you want to see an ex ...

As the value steadily grows, it continues to rise without interruption

Even though I thought it was a simple issue, I am still struggling to solve it. What I need is for the output value to increment continuously when I click the button. Here is the code snippet I have been working on: $('.submit').on('click&a ...

Using ng-click to manipulate variables within a list

In my ionic/angular/phonegap app, I have a list of items and I'm attempting to use an action sheet to pass in the variables. However, I am having trouble accessing the variable on the same line as the ng-repeater. Here is the markup: <ion-view vi ...

Cookie Multitree: An Innovative JsTree Solution

Hello everyone, I am currently using jstree and have come across a couple of issues with having multiple trees on the same page. Here are my two problems: 1) I am looking to implement cookies to keep track of which nodes are open in each tree. I attempted ...

Trouble with a basic Angular demonstration

After replicating an angular example from w3schools (found here), I encountered some issues with it not functioning correctly. Despite my efforts, the code appears to be accurate. Can anyone spot what might be going wrong? To provide more context, here is ...

Issue encountered with Fabric js: Unable to apply pattern fill to a group of rectangles

Greetings, I am in need of some assistance with a coding issue. I have a for loop that generates and adds multiple rectangles to a fabric js canvas. To set a texture for each rectangle, I am using the following code snippet. var rect = new fabric.Rect( ...

Angular form validation within an ng-repeat is malfunctioning

I'm struggling to implement validation using an ng-repeat statement. Below is the code I have so far. I want to apply the has-error class to the div.form-group when the name field is empty, but it's not working for me. Any suggestions on how to f ...

Unable to locate the module 'true-case-path'

I am encountering an issue when trying to start npm. The error message I am receiving is as follows: E:\angular2\projects2018\angularFlex>npm install > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b ...

Ensuring Input Integrity: Utilizing HTML and Javascript to Block Unfilled Form Submissions

Currently, I am working on developing a registration page using HTML and JavaScript. Although I have added the 'required' tag in HTML to prevent users from submitting empty input fields, I noticed that users can bypass this restriction by simply ...

Ways to extract information immediately after using the .load method

Is there a way to instantly store data from .load in JavaScript? Whenever I use .load within a JavaScript function to retrieve content from the server and display it on the browser page, the content does not update immediately. It's only when the fu ...

"Discover the process of sending a JSON value from a PHP page to an HTML page using AJAX, and learn how to display the resulting data

I am currently validating an email ID using PHP and AJAX, with the intention of returning a value from the PHP page to the HTML in JSON format. My goal is to store this return value in a PHP variable for future use. All of this is being executed within C ...

How to display 3 items per row in a React table by utilizing a map function loop

Currently, my table using material UI generates one column on each row. However, I would like to display 3 columns as items on each row. Below is the mapping for my table: <TableBody> {this.props.data.slice(page * rowsPerPage, page * rowsPerPage ...

The ReactJS component is unable to resolve the specified domain name

Whenever I utilize a component like const React = require('react'); const dns = require('dns'); class DnsResolver extends React.Component { componentDidMount() { dns.resolve('https://www.google.com', (err, addres ...

What is the best way to pick an option from a dropdown menu using angularjs?

Is there a way to select an item from a dropdown list in AngularJS without using ng-repeat with an object array? I can easily select an option when using ng-repeat, but how can this be achieved with a normal select list? <select class="form-control" ...

The addition of input fields on keyup creates problems in the initial field of each row

I am currently working with a table and attempting to calculate the sums as follows: td(1) + td(2) + td(3) = td(4), td(5) + td(6) + td(7) = td(8), td(9) + td(10) + td(11) = td(12). This is the code I have implemented: $(document).ready(function () { ...