When you click away from the div in AngularJS, it will automatically disappear

Whenever we click outside the div or in a window, the xyz should be hidden.

const app = angular.module('myApp', []);  
   app.controller('myCtrl', function($scope) {  
        $scope.showDropdown = false;
     $scope.helloClick = function(){
        if($scope.showDropdown === true){
            $scope.showDropdown = false;
        }
        else{
            $scope.showDropdown = true;
        }
     }
  });

Check out my code on JSFiddle: https://jsfiddle.net/8ftrnenw/

Answer №1

Here is the solution you requested:

  • I implemented a custom directive
  • This directive, named click-outside, listens for clicks on elements where it is applied.
  • If the click occurs outside of the targeted element, it will hide the specified div

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   $scope.showDropdown = false;
   $scope.hide = function(){
     $scope.showDropdown = false;
   }
   $scope.helloClick = function(){
  $scope.showDropdown = !$scope.showDropdown;
  }
}

});
app.directive('clickOutside', function ($document) {

        return {
           restrict: 'A',
           scope: {
               clickOutside: '&'
           },
           link: function (scope, el, attr) {

               $document.on('click', function (e) {
                   if (el !== e.target && !el[0].contains(e.target)) {
                        scope.$apply(function () {
                            scope.$eval(scope.clickOutside);
                        });
                    }
               });
           }
        }

    });
.xyz{
border:1px solid red;
width:200px;
height:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div  click-outside="hide()">
<div class="hello" ng-click ="helloClick()">hello</div>
<div class="xyz"  ng-if="showDropdown">xyz</div>
</div>
</div>

Please test the above code snippet

Take a look at the live DEMO

Note about the directive:

el !== e.target && !el[0].contains(e.target)

Here, 'e' represents the clicked element and 'el' is the element to which the directive is attached. This condition checks if the clicked element is not the same as the target element with the directive. If not, it will hide the specified div

scope.$eval(scope.clickOutside);

This line evaluates the attribute and triggers the function provided in click-outside="hide()"

Answer №2

Shout out to @Sravan for the helpful suggestion. I've made an enhancement to ensure that this event is only triggered when the target component is visible.

app.directive('clickOutside', function ($document) {

  return {
    restrict: 'A',
      scope: {
        clickOutside: '&',
        launchEvent: '='
  },
  link: function (scope, el, attr) {

    var launched = false;

    scope.$watch('launchEvent', function (newVal) {

      if (newVal && !launched) {

        launched = true;

        $document.on('click', function (e) {
          if (el !== e.target && !el[0].contains(e.target)) {
            scope.$apply(function () {
              scope.$eval(scope.clickOutside);
            });
          }
        });
      } else {
        launched = false;
        $document.off('click');
      }

    });
  }
}

});

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

Transforming a collection of objects into proper JSON format for seamless transmission in an ajax request

I'm struggling to understand why I keep encountering the 'Unexpected end of JSON input' error when attempting to stringify an object array and passing it to an ajax call. $(document).on("click", "#frmcomplist_cmdPrint", function(){ let com ...

Tips for showcasing a drop-down menu using Jquery

I am currently utilizing jQuery to showcase a drop-down menu. It is successfully working for a single menu and displaying the appropriate drop-down. However, when I attempt to use more than one menu, it displays all of the drop-down menus simultaneously. I ...

Transform audio file into a base64 encoding

I am currently developing a Phonegap application for a friend that will allow users to record audio on their phone, save it to the browser's local storage, and then upload it at a later time. As far as I know, local storage does not support storing b ...

Change of weekly scheduled date for hyperlink url

Each week, I release a newsletter with a consistent file path and similar file name except for the date. The newsletter is published every 7 days, requiring me to update the link by adding 7 days to the date each time. It's important that the date is ...

Tips for retrieving input values when they are not available in HTML documents

In this code snippet, I am creating an input element with the file type without adding it to the DOM. My goal is to retrieve the value of this input once the user selects a file. Even though the input is not part of the HTML template, I still want to acces ...

Discovering the FindOne() model in Nodejs Sequelize comes with values that are either rounded or truncated

Running the code below, I am attempting to retrieve data from an sqlite database connected to locally. The current snippet is a test to fetch data: console.log('debug after here.'); const tag = await Tags.findOne({ where: { guild: message.guild ...

Setting the width of individual Views within a ScrollView to adjust accordingly in React Native

Is there a way to ensure that the Views inside my horizontal ScrollView have the same dimensions as the ScrollView itself? I'd like to implement paging so that swiping takes me to the next View within the ScrollView. I attempted using width : "100%" b ...

I'm having trouble getting the animation to work with jQuery. Despite trying everything, the animation doesn't seem to respond to any button clicks

Issue: I am facing a problem where nothing happens when I click the menu on the HTML page. It seems like a total beginner mistake, but I can't seem to get it to work. I have checked the code, and alert works fine, indicating that jQuery is connected t ...

Yaml scripting for BunJs CLI commands

Are there any CLI tools in bun.js that are capable of interpreting Yaml scripts? Similar to how npm processes package.json files in node.js, allowing script definition and execution from the command line interface, but with Yaml being a more readable form ...

Is it possible to send arguments to the functions executed by "jQuery then"?

Check out the complete code here: http://jsfiddle.net/BurFz/ http://jsbin.com/dagequha/1/edit?js,console /** * executed function chain */ func1('arg1').then(func2).then(func3).then(function () { console.log('execution comp ...

Inject nested controller dynamically

I am working on a straightforward ASP.NET MVC application that includes an ng-controller. I am trying to inject another ng-controller inside this controller using a partial view, but I'm having trouble getting the binding to work correctly. You can s ...

Is it possible to extract a div from a third-party domain and showcase it on my website?

Trying to integrate content from my Veetle.com channel onto my personal website has proven to be quite the challenge. Initially, I attempted to modify an iframe with CSS to display only the schedule information, but encountered limitations due to using 3rd ...

Unable to access contextual values in NextJS

When attempting to retrieve values from the context API, I am encountering issues where I receive a default value (without the updates made during the context call) and an undefined value (which should receive a value in the context provider). sortListCont ...

Guide to launching my application by clicking on a file from a local device using React Native

Currently, I am working with React Native and Expo. I have a file with a unique extension (let's say: SomeFileName.xxx) which contains some text. My goal is to open this file from the device in such a way that it launches the application (either on An ...

The suggestions for auto-complete in jQuery are not showing up as expected

I am looking to implement a feature where suggestions from the database are automatically populated in a text box as I type. Additionally, when I select a suggestion, other related text fields should be filled automatically. Below is the code snippet: Vi ...

Is it possible to extract a user's password from the WordPress database for use in a React application

Is it feasible to create a React application integrated with Postgres within Wordpress that operates on MySql? I am interested in leveraging Wordpress's built-in features for theming, posts, and user management accounts. However, I am unsure if I can ...

An issue occurred: The property 'postFeedback' cannot be read as it is undefined

Version of Angular and Node : Angular CLI: 6.2.9 Node: 8.17.0 An error is being thrown with a stack trace when clicking on the Send Feedback button: ERROR TypeError: Cannot read property 'postFeedback' of undefined at FeedbackComponent.push../ ...

Encountering an 'unresolved variable' error related to a variable utilized in the preceding line (PHPStorm 2018.2.5)

I'm facing a challenge in my IDE while working on a simple code. I'm currently using Angular 1.4 and ES 5.1. function myFunction() { var vm = this; vm.listResults = null; SomeService.someFunction() .then(function (result) { ...

Tips for including arguments in pm2 file execution

What steps should I take to run the cluster.js file on pm2 successfully? When I try executing the file locally with 'node cluster.js 0 1' command, it appends two arguments but encountering an error when using 'pm2 start "cluster.js 0 1"&apos ...

Is there a way to utilize namespace import without bringing in all the other imports as well

Within our angular application built with typescript, we make use of lodash. Our current approach to importing lodash is demonstrated below: import * as _ from 'lodash'; //.. code which utilizes _.pluck() However, in order to optimize for tree ...