Automatically close the multiselect dropdown when the user interacts outside of it (varied scenario)

For those interested, check out this jsfiddle link: http://jsfiddle.net/jaredwilli/vUSPu/

This specific code snippet focuses on creating a multi-select dropdown feature. When a user chooses options from the dropdown and then clicks outside of the menu area, the list does not automatically close. Is there a way to make it so that the dropdown closes when the user clicks anywhere else besides the dropdown itself?

<div ng-app="myApp" ng-controller="AppCtrl">
<dropdown-multiselect pre-selected="member.roles" model="selected_items" options="roles"></dropdown-multiselect>

<pre>selected roles = {{selected_items | json}}</pre>

'use strict';

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

app.controller('AppCtrl', function($scope){
$scope.roles = [
      {"id": 1, "name": "Manager", "assignable": true},
      {"id": 2, "name": "Developer", "assignable": true},
      {"id": 3, "name": "Reporter", "assignable": true}
];

$scope.member = {roles: []};
$scope.selected_items = [];
});

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

app_directives.directive('dropdownMultiselect', function(){
return {
   restrict: 'E',
   scope:{
        model: '=',
        options: '=',
        pre_selected: '=preSelected'
   },
   template: "<div class='btn-group' data-ng-class='{open: open}'>"+
    "<button class='btn btn-small'>Select</button>"+
            "<button class='btn btn-small dropdown-toggle' data-ng-click='open=!open;openDropdown()'><span class='caret'></span></button>"+
            "<ul class='dropdown-menu' aria-labelledby='dropdownMenu'>" +
                "<li><a data-ng-click='selectAll()'><i class='icon-ok-sign'></i>  Check All</a></li>" +
                "<li><a data-ng-click='deselectAll();'><i class='icon-remove-sign'></i>  Uncheck All</a></li>" +
                "<li class='divider'></li>" +
                "<li data-ng-repeat='option in options'> <a data-ng-click='setSelectedItem()'>{{option.name}}<span data-ng-class='isChecked(option.id)'></span></a></li>" +
            "</ul>" +
        "</div>" ,
   controller: function($scope){

       $scope.openDropdown = function(){
                $scope.selected_items = [];
                for(var i=0; i<$scope.pre_selected.length; i++){                        $scope.selected_items.push($scope.pre_selected[i].id);
                }
        };

        $scope.selectAll = function () {
            $scope.model = _.pluck($scope.options, 'id');
            console.log($scope.model);
        };
        $scope.deselectAll = function() {
            $scope.model=[];
            console.log($scope.model);
        };
        $scope.setSelectedItem = function(){
            var id = this.option.id;
            if (_.contains($scope.model, id)) {
                $scope.model = _.without($scope.model, id);
            } else {
                $scope.model.push(id);
            }
            console.log($scope.model);
            return false;
        };
        $scope.isChecked = function (id) {
            if (_.contains($scope.model, id)) {
                return 'icon-ok pull-right';
            }
            return false;
        };
   }
   }
});

Answer №1

After exploring the jsFiddle you shared, I understand your perspective. I believe this suggestion could be beneficial for your situation.

By delving into a bit of searching, one can uncover many solutions :)

Check out this link for insights on hiding an AngularJS dropdown directive when clicking outside

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

Can you explain the concept of a framework operating "on top of" node.js in a way that would be easy for a beginner to understand?

If someone is new to JavaScript, how would you explain the concept of "on top of node.js" in simple programming language? I am looking for a general explanation as well as specific reference to Express on top of node.js in the MEAN stack. Appreciate your ...

extracting ng-repeat values and passing them to the controller

I have created a form that dynamically increases whenever the user clicks on the add sale button Here is the HTML code: <fieldset data-ng-repeat="choice in choices"> <div class="form-group"> <label for="name"> Qu ...

Ways to transfer JavaScript arguments to CSS style

Currently, I am developing a web service using Angular and Spring Boot. In this project, I have implemented cdkDrag functionality to allow users to place images in specific locations within the workspace. My goal is to maintain the placement of these image ...

Is it no longer possible to export static pages in Next.js 14?

I'm currently experiencing a problem where my CSS styles are not being exported when I try to convert my project into static HTML pages. Here is the configuration in my next.config.js file: ** @type {import('next').NextConfig} */ const next ...

"CSS styles applied to the body element do not automatically transfer to the h1

Explore the World of Coding: <body class="pageDesign"> <h1>CSS - A Creative Journey</h1> <p><strong>Discover the beauty of coding</strong> and unlock a world of possibilities with CSS. Let your imagination soar as you d ...

When you drag down on mobile Safari on an iPad, touch events may cease to fire in HTML5

When I implement event listeners to handle touch events like touchmove and touchstart document.addEventListener("touchstart", function(event){ event.preventDefault(); document.getElementById("fpsCounter").innerHTML = "Touch ...

Retrieve the desired element from an array when a button is clicked

When I click on the button, I need to update an object in an array. However, I am facing difficulties selecting the object that was clicked. For better readability, here is the link to my GitHub repository: https://github.com/Azciop/BernamontSteven_P7_V2 ...

Display a message if the local storage is empty

Recently, I came across a javascript code snippet that is designed to save birthday data in local storage and then display the data within a div element. The current functionality only shows nothing if the storage is empty. However, I require it to display ...

javascript: window.open()

I am currently using VB.NET 2005 and I have a requirement to launch a new browser window using Process.Start(). The challenge is that I need to specify the size of the browser window, for example, height:300 and width:500. Process.Start("firefox.exe", "ab ...

Querying MongoDB with a JavaScript file for formatting datetime values

I am utilizing mongodb3.0.5 and my database collection appears as follows: { "_id" : "xxxxxxxxxxxxxxx", "SchoolId" : 1, "ActivationTimestamp" : ISODate("2015-09-22T13:01:58.000Z"), "PersonDetails" : [ { "Name" : "John" ...

Creating AngularJS select boxes with varying sizes and values within an ng-repeat loop

I've identified the issue, but my attempts to resolve it have been unsuccessful so far. Any assistance would be greatly appreciated. Currently, I am working on generating a table from JSON data within an ng-repeat loop. One of the columns in the tabl ...

Streamline your processes by automating jQuery AJAX forms

I am looking to automate a click function using the code snippet below in order to directly submit form votes. Is there a method to develop a standalone script that can submit the votes without requiring a webpage refresh: <input type="submit" id="edit ...

Interactive input field designed for modifying, adding, and removing data in MySQL

I am working on a project where I have a simple form. However, I need to dynamically change the form action from insert to update within the same page. Additionally, I also want to display the values on the same page. Within my code, I have set up the up ...

"Create a dynamic and user-friendly responsive navbar using Bootstrap with toggle

I need assistance with creating a new project template to convert a WordPress template into a Bootstrap template. Currently, I am working on the navbar and facing issues with responsive design and toggle navigation. On laptop devices, the navbar looks goo ...

The scripts on Prerender.io were not loaded properly

I am facing an issue with my JavaScript files. I have two separate files: vendor.js - containing angular.js and other libraries; app.js - consisting of my own code. However, when I load them separately, the page does not open as expected during pre ...

Remove all links with a specific class within a <div> element, excluding the one that was clicked

Is there a way in jQuery to manipulate all links inside a <div> by removing/disabling or changing their classes, except for the one that was clicked? I need to change the class of the clicked link while potentially hiding or altering the others. < ...

The issue of using an import statement outside a module arises when executing Protractor

I am facing an issue while running Protractor with my two files. When I execute the command "protractor protractor.config.js", I encounter the following error: D:\work\staru-app>protractor protractor.config.js [16:57:17] I/launcher - Running ...

Acquire the selected option's value and display it within a div container

Is there a way to extract and display only the price value (after the " - ") within a div with the id of "price", updating as the select element is changed? <select id="product-select" name=""> <option value="1">Product Name / Yellow / S - ...

Generating Dynamic Widgets Within the Document Object Model

Currently, I am working with jQuery Mobile 1 alpha 1. In order to create a text input field using jQuery Mobile, you need to include the following HTML code: <div data-role='fieldcontain'> <label for='name'>Text Input:</ ...

Struggling to find a solution to adjust an Angular directive

I am attempting to create a functionality where, upon clicking a button, the user can select one of two images displayed and make the selected image draggable. Currently, my code displays two images with only one being draggable. I am struggling to impleme ...