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

What is the reason behind Svelte not scoping the tag under a class, but instead using individual tag.class to style a component?

It is common practice to scope CSS styles for components like this: .my-component-01 h1 { ... } .my-component-01 h2 { ... } However, Svelte takes a different approach by applying the styles directly to the tags: h1.svelte-hlsza1{color:orange} h2.svelte- ...

"Troubleshooting the issue of jQuery addition not functioning correctly within an AJAX

Is there a way to add the result value to an already existing value in a specific textbox? I've noticed that concatenation is working, but addition is not. $.post('includes/ajax_timesheet.php', { 'action': 'add_kitamount&ap ...

What could be the reason for the mouseleave event not functioning properly?

I have a JSFiddle that is working perfectly. Check out my Fiddle here. In my code, I am trying to make a div change colors when hovered over and then back to its original color when the mouse moves out. It works fine on JSFiddle but not locally. When I r ...

What is the importance of having the retrieved module name match the module name passed as the first argument in the Angular.module function?

I have developed a program that utilizes angular modules. I have defined a module as shown below: // Module A var modA = angular.module("moduleA",[]); //Controller A modA.controller("AController", function($scope, $rootScope, $log){ $log.info("In cont ...

Concealed Selenium File Upload through Drag and Drop User Interface

Struggling to insert an image into the specified input using selenium web-driver. <input type="file" multiple="multiple" class="dz-hidden-input" accept="image/gif,image/jpg,image/jpeg,image/png,application/zip" style="visibility: hidden; position: abso ...

supplying various color variables to a single class

I am working on a webpage with multiple elements sharing the same CSS class. I want each element to have a unique background color, but I don't want to create a bloated CSS file. Is there a way to achieve this by adding a parameter in my HTML like cla ...

Violation of Content Security Policy directive has occurred

During my full-stack project development, I encountered an issue with the inclusion of the bundle.js file in my base HTML file using a simple script tag. When trying to render the page and utilize the JS functionality, I faced a content security policy vio ...

Utilizing cloud functions to distort an inappropriate image

I have a requirement to analyze any uploaded image for inappropriate content and blur it if necessary. The log this image is inappropriate indicates that the detection process is working correctly. However, I am not able to see any further logs which sugg ...

How to showcase numerous PDF documents within a ReactJS application

As a newcomer to the world of React, I am facing an issue with displaying multiple PDFs based on the selected link. Although I have been successful in displaying a PDF from a list of links pointing to my stored PDFs within the src directory, I encounter th ...

I am interested in verifying the presence of a user

Below is the form for checking user existence using AJAX: <!DOCTYPE html> <html> <head><title>Register new user!</title> <script src="jquery-1.7.1.min.js"></script> </head> <body> ...

Arrange a cluster of CSS table cells onto a fresh line

Currently, I am exploring CSS properties to create the visual appearance of a table using two levels of DOM elements. The highest-level element wraps around its child elements, which are styled to resemble a flat list. For example: <div class="t"> ...

JavaScript - Retrieve a nested property within an object using an array of strings

I possess an object in the following format { metadata: { correlationId: 'b24e9f21-6977-4553-abc7-416f8ed2da2d',   createdDateTime: '2021-06-15T16:46:24.247Z' } } and I possess an array containing the properties I wish to re ...

Unable to execute $http in AngularJS Plunker

Having trouble running $http on the Plunker. Can you please review my code and assist me? var QuizApp = angular.module('QuizApp', []); QuizApp.controller('QuizController', ['$scope','$http',function($scope,$http) { ...

Converting an array of objects into an array of Objects containing both individual objects and arrays

I am dealing with an object const response = { "message": "story records found successfully", "result": [ { "created_AT": "Thu, 13 Jan 2022 17:37:04 GMT", ...

Error encountered while using JavaScript for waiting in Selenium

When using selenium and phantomjs to submit a form and then navigate back to the previous page, sometimes I encounter a timeout error as shown below: TimeoutError: Waiting for element to be located By(xpath,//div[@id='ContactFormBody']/div/br) W ...

The user is defined, but the user's user ID is not specified

It seems that the user is defined, but user.user_id is not. My framework of choice is express.js and passport.js. router.post('/requestSale', function(req,res){ console.log('session user: ' + req.session.passport.user); //logs ...

Exploring characteristics within a Three.Js environment in a React application

I have successfully integrated a ThreeJs Scene into a React component, following the approach outlined here. However, I am facing difficulties updating the Scene based on state changes in its parent component. In my setup, users can configure certain prope ...

Is Axios the sole option for API calls when utilizing Next.js with SSG and SSR?

Can someone clarify the best practice for data fetching in Next.js? Should we avoid using axios or other methods in our functional components, and instead rely on SSG/SSR functions? I'm new to Next.js and seeking guidance. ...

Cast your vote once for each post within the Angular application

Currently, users are only able to vote up or down once in general. I would like to allow users to vote up or down once per post. <div ng-repeat="post in posts | orderBy:'-upvotes'"> <span class="glyphicon glyphicon-thumbs-up" ...

Ways to implement a scrollable v-list component using Vuetify

I have set up a v-list using flex layout, where the v-list expands to fill the remaining space horizontally in a column. However, if the list contains many elements with a total height that exceeds the column's height, the list ends up sticking out of ...