Switching between custom dropdowns in Angular

I've implemented a custom dropdown selector with the functionality to toggle when clicked anywhere else on the browser. The toggleModules() function is responsible for handling the toggling within the dropdown.

Data:

modules=["A", "B", "C", "D", "E", "F"]

<div class="col-xl-3 col-lg-3 col-md-3 col-sm-12">
    <div class="vov-filters ov-filter-region">
        <span ng-click="toggleModules($event)"><label>Module</label>
            <b id="caret-glyph" class="glyphicon glyphicon-chevron-down pull-right" area-hidden="true"></b>
        </span>

        <div id="el1" class="overlay bordered" ng-if="showModules">
            <span role="button" ng-click="clearSelectedModules()" class="clear">Clear</span>
                <div class="filter-checkbox" ng-repeat="entry in modules" ng-click="moduleFilter(entry)">
                    <label>
                        <input ng-show="entry.show" type="checkbox" ng-model="entry.show">
                        <span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>
                        {{entry.name}}
                    </label>
                </div>
            </div>

        </div>
    </div>

controller: Toggle fn -

  $scope.toggleModules = function(ev) {
      ev.preventDefault();
      ev.stopPropagation();
      $scope.showModules = !$scope.showModules;
      if ($scope.showModules) {
        $scope.overlay = true;
      } else {
        $scope.overlay = false;
      }
    };

Same Contoller: $document Click Event:

$document.on('click', function(event) {
  <!-- Start Toggle Module filter -->
  $scope.toggleModules(event)
  <!-- End Toggle Module filter -->
  return $document.off('click', event);
});

Answer №1

Appreciate your help everyone. I managed to get a solution that is working perfectly for my needs.

$document.on('click', function(event) {
    event.preventDefault();
    event.stopPropagation();
    $scope.$apply(function() {
        $scope.showModules = false;
    });
    $document.off('click', event);
});

Answer №2

A custom click-off directive can be implemented to detect a click outside of a specific div element and trigger a desired action.

myApp.directive('clickOff', function($parse, $document) {
var dir = {
    compile: function($element, attr) {
      // Parse the expression provided to execute when clicked outside this element.
      var fn = $parse(attr["clickOff"]);
      return function(scope, element, attr) {
        // Add a click handler to the element to stop event propagation.
        element.bind("click", function(event) {
          console.log("stopProp");
          event.stopPropagation();
        });
        angular.element($document[0].body).bind("click", function(event) {
            console.log("cancel.");
            scope.$apply(function() {
                fn(scope, {$event:event});
            });
        });
      };
    }
  };
  return dir;
});

Check out this fiddle for a demonstration!

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

Unexpected token N error was thrown while using the Jquery .ajax() function

While working on a form submission feature using JQuery .ajax() to save data into a MySQL database, I encountered an error message that says "SyntaxError: Unexpected token N". Can someone please explain what this means and provide guidance on how to fix it ...

Angular 6 TypeScript allows for efficient comparison and updating of keys within arrays of objects. By leveraging this feature

arrayOne: [ { id: 1, compId: 11, active: false, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ] arrayTwo: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 33, active: false, ...

Maintain course focus when updating

I'm currently working on a to-do list where clicking on an item adds the "checked" class. However, when I refresh the page, everything reverts back to its original state without the checked class. How can I maintain the state of the checked items? I& ...

Retrieve the URL of an image located within an <li> tag within a jQuery selector item array

I am currently using a jQuery slider plugin to display images, and I am attempting to retrieve the URL of the current image when a button is clicked. The slider functions by showcasing all the image slides as list items in a continuous horizontal row. It ...

Why is it that this particular line of code sometimes gives me an "undefined" result before returning an actual value?

Why does the method 'equal' always return with an "undefined" followed by a number? And when I try to parse it, it returns me a NaN. <!DOCTYPE> <html> <head> <script> var fnum = 0; var secondNum; var operation; functi ...

What is the best way to set a new value in AngularJS?

I attempted to connect the values of msg1 and msg2 like this, and it worked as expected. When I change the input text value of msg1, msg2 also changes to the same value as msg1. Javascript var BindController = function($scope){ $scope.msg1; $scop ...

The dollar sign function operates properly, but encountering issues with the $.ajax function (non-slim)

I'm facing some issues with my jQuery code. I have included jQuery (not slim) and for some reason, $.ajax is failing. However, '$' and 'jQuery' functions are working fine. It seems like a simple problem but I can't seem to fi ...

Unlocking the Power of Angular: Understanding the Relationship between Controllers and Directives

Currently delving into the world of Angular and encountering a hurdle in accessing controller scope from a directive. The $scope.vojta has already been populated in the controller, but I'm unable to print it from the directive. <div ng-controller= ...

What is causing Puppeteer to not wait?

It's my understanding that in the code await Promise.all(...), the sequence of events should be: First console.log is printed 9-second delay occurs Last console.log is printed How can I adjust the timing of the 3rd print statement to be displayed af ...

Elements on the page are quivering as a result of the CSS animation

When a user clicks anywhere on a div, I have added a ripple effect to give it some interaction. However, there is an issue where the element shakes and becomes blurry when the page is in full screen mode until the ripple effect disappears. Below is the Ja ...

Parsing JSON data to extract values stored in a two-dimensional array

In order to develop a basic version of Tic Tac Toe, I decided to store game data in a JSON file. Here is an example of how the file is structured: [ { "turn": "x", "board": [ [ " ...

In order to display the particle-slider logo effect, the JavaScript on the page needs to be refreshed

I have a website frontend integrated from WordPress using an HTML 5 Blank Child Theme. The site features a logo effect utilizing particle slider for screen sizes greater than 960px, and a flat logo image for screen sizes less than 960px. Everything works p ...

The formatter/render function in Angular Directive fails to refresh

Recently, I created a straightforward directive that converts minutes into a range slider while also displaying hours and minutes alongside. However, I encountered an issue where although moving the range slider updates the scope triggering Watch and Pars ...

Dealing with incorrect routes found in both documents

In my current project, I am facing an issue where I need to handle invalid routes and display a message in Node.js. I have two separate files, one for users and one for tasks. If a user accesses a route that does not exist, I want to show an error message ...

It is not possible to recycle a TinyMCE editor that is embedded in a popup

Having a frustrating issue with the TinyMCE Editor plugin embedded within a Fancybox pop-up window. I have a list of objects with Edit links that trigger an AJAX call to retrieve content from the server and place it in a <textarea>. A TinyMCE editor ...

Displaying an error message: Uncaught ReferenceError - Undefined reference detected

Hi there, I am having some trouble with a JSON file and I would appreciate some help. The error message I am receiving is: Uncaught ReferenceError: marketlivedata is not defined <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquer ...

Deleting object property within Angular ng-repeat loop

I have information structured like this: $scope.cart={"4": {"cost": 802.85, "description": "test", "qty": 1}, "5": {"cost": 802.85, "description": "test", "qty": 1}}; My goal is to iterate through this data and show it with a remove button. How can I s ...

The issue with the NextJS Layout component is that it is failing to display the page content, with an error message indicating that objects cannot be used

I am embarking on my first project using Next JS and after watching several tutorial videos, I find the Layout component to be a perfect fit for my project! However, I am encountering an issue where the page content does not display. The Menu and Footer a ...

CSS and JavaScript Nav Menu Collapse (No Bootstrap)

I have written a navbar code using pure HTML/SASS, but I am facing a challenge in adding a collapse element to the navigation bar. Despite trying various solutions from Stack Overflow, I still haven't found one that works for me. Therefore, I am rea ...

Select the send all text option when making a request

Using ajax, I can dynamically fill a drop-down select menu. My next step is to include all the text from the selected options in my request. <select name=".." > <option value="0"> ... </option> <option value="1"> xxx </option ...