Ways to conceal submenu when clicking away from the navigation bar

I am looking to create a directive that will generate a navigation bar. Check out my code on JSFiddle here.

Here is the code snippet from index.html :

<html lang="fr" ng-app="activity" id="ng-app">    
    <div  ng-controller="mainCtrl">
        <navigation-bar datas ="data"> </navigation-bar>
    </div>
</html>

This is the directive I have created:

app.directive('navigationBar', ['$window', function ($window) {

        return {
            restrict: 'EA',
            template: "<div id='navigation' class='navigation'>"+
                "<ul id='navidationUl' name='navigationName'> "+
                    "<li id='navLi' ng-repeat='(key, value) in datas'>"+
                        "<a  ng-href='{{value.route}}' ng-click='toggle($index)'> {{value.libelle}} "+
                            "<span ng-if='value.subMenu.length > 0' class='caret'></span>"+
                        "</a> "+
                        "<ul  id ='subMenu' ng-show ='value.showMe && value.subMenu.length > 0'>"+
                            "<li ng-repeat='(key2, value2) in value.subMenu'>"+
                                "<a ng-href='{{value2.route}}' ng-click ='dismissAll()'>{{value2.libelle}}</a>"+
                            "</li>"+
                        "</ul>"+

                    "</li> "+
                "</ul>"+
            "</div>",
            scope: {
                datas : "=datas"
            },
            link: function (scope, elem, attrs) {
                console.log("LINK : ", scope, elem, attrs);
                scope.dismissAll = function (){
                    for(var i = 0; i< scope.datas.length; i++) {
                        scope.datas[i].showMe = false;
                    }
                }
                scope.toggle = function toggle(index){
                    scope.datas[index].showMe = !scope.datas[index].showMe;
                    for(var i = 0; i< scope.datas.length; i++) {
                        if (i !=index) {
                            scope.datas[i].showMe = false;
                        }
                    }
                };
            }
        };
}]);

I am trying to figure out how to hide the sub-menu when the user clicks outside of the navigation bar.

Answer №1

To ensure all menus are hidden when clicking globally, you can implement the following method:

app.directive('navigationBar', ['$window', '$document', function ($window, $document) {

    return {
        restrict: 'EA',
        template: "<div id='navigation' class='navigation'>"+
            "<ul id='navidationUl' name='navigationName'> "+
                "<li id='navLi' ng-repeat='(key, value) in datas'>"+
                    "<a  ng-href='{{value.route}}' ng-click='toggle($index)'> {{value.libelle}} "+
                        "<span ng-if='value.subMenu.length > 0' class='caret'></span>"+
                    "</a> "+
                    "<ul  id ='subMenu' ng-show ='value.showMe && value.subMenu.length > 0'>"+
                        "<li ng-repeat='(key2, value2) in value.subMenu'>"+
                            "<a ng-href='{{value2.route}}' ng-click ='dismissAll()'>{{value2.libelle}}</a>"+
                        "</li>"+
                    "</ul>"+

                "</li> "+
            "</ul>"+
        "</div>",
        scope: {
            datas : "=datas"
        },
        link: function (scope, elem, attrs) {
            scope.dismissAll = function (){
                for(var i = 0; i< scope.datas.length; i++) {
                    scope.datas[i].showMe = false;
                }
            }
            scope.toggle = function toggle(index){
                scope.datas[index].showMe = !scope.datas[index].showMe;
                for(var i = 0; i< scope.datas.length; i++) {
                    if (i !=index) {
                        scope.datas[i].showMe = false;
                    }
                }
            };

            elem.bind('click', function(e) {
                // this part keeps it from firing the click on the document.
                e.stopPropagation();
            });
            $doc.bind('click', function() {
                scope.$apply(scope.dismissAll);
            })
        }
    };
}]);

For further details, visit: Angular Click outside of an element event

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

Is it a scope issue if ng-click is not firing and the function is not working properly?

I'm facing an issue with an animation that is not working as intended. The goal is to have the search button trigger an animation to pull a search bar from the right side, allowing users to input their search query. However, the ng-click function does ...

Guide on setting up a new NPM and JavaScript project within Visual Studio 2015

Whenever I watch tutorials, they always mention having a "special npm reference" that I seem to be missing. https://i.sstatic.net/I52dn.png All I can find are the "normal" references (.net assemblies). I also can't locate any project type labeled as ...

Updating an array in JavaScript with a dynamically generated key name while working in the ReactJS framework

I have multiple dropdown menus, and when I select an option from any of them, I want to store the selected value in the component state. The onChange function that I call looks like this: function handleSelect(event) { console.log(event.target.value); ...

Anchor point located within a scrollable div with a fixed position

A unique challenge has presented itself with a div called #results that appears when words are entered into a text box, triggering relevant results. This particular div is fixed and scrollable, with pagination located at the bottom of the scroll. The iss ...

Utilizing HTML5 to automatically refresh the page upon a change in geolocation

I have a web application built with AngularJS. One of the functionalities is activated only when the user is in close proximity to specific locations. To make this work, I can constantly refresh the page every 5 seconds and carry out calculations to dete ...

A step-by-step guide on how to exclusively print items that have been selected using a checkbox in AngularJS

I have created two tables and added a checkbox for each one. Instead of default checkboxes, I have used images that change when clicked. Here is the code snippet: <button class="btn btn-lg btn-customPrint-md no-print" ng-click="checkBoxPrint2 = !check ...

Attempting to nest an AJAX request within the success callback of another AJAX request

I am attempting to execute two jQuery ajax calls, with the second call being made from the success callback of the first. I have experimented with different variations of the code, such as adjusting the brackets. Below is my attempted code snippet: $.aja ...

ngModel.$setValidity is a one-time operation

Currently, I am working on a validation issue with an angular bootstrap ui datepicker popup. I have set the max and min dates for validation, which work when the user selects a date from the calendar. However, if the user manually inputs a date, these vali ...

Discord bot that combines the power of discord.js and node.js to enhance your music

I am currently working on a Discord bot designed to play music in voice chat rooms. However, I am facing some issues with properties. Whenever I try to launch the bot using "node main", I encounter the following error message: "TypeError: Cannot read prope ...

Utilizing ng-options to dynamically populate a select element with data received from a

Currently, I am receiving a promise in the following manner. GetAgentsPromise.then(function(response) { GetAgentsPromise.then(function(response) { $scope.ClientAgents.id = response.data.d.AgentIDs; $scope ...

How Can You Change the Position of a Threejs Vector3?

I'm attempting to create bones and then manipulate the vertices of each bone, but I am struggling with the correct syntax. Here is an example of what I have tried: var v = new THREE.Vector3(0,0,0); var b = new THREE.Bone(); b.position.x = 5; b.positi ...

When the FileReader reads the file as readAsArrayBuffer, it ensures that the correct encoding is used

Currently, I am developing a script in JavaScript to read uploaded .csv/.xlsx files and convert the data into an array containing each row. Using FileReader along with SheetJs, I have successfully managed to achieve this by implementing the following code: ...

Determine the number of days without including weekends and holidays using JavaScript

I am working on a code that calculates the total number of days excluding weekends and specified holidays. After researching on various platforms like stackoverflow and adobe forum, I have come up with the following code. If a public holiday falls on a w ...

Retrieving JavaScript return values in a C# WebBrowser control within a WPF application

I utilized JavaScript injection into WebBrowser control in C# (System.Windows.Controls.WebBrowser) to achieve, <C#> IHTMLDocument2 webdoc = (IHTMLDocument2)webBrowser1.Document; string var = File.ReadAllText("C:/.../Resources/script.txt"); object re ...

Checking for the existence of a Vue.js component

In the ready: method of the root instance, I have certain tasks to perform but only if some components are not present (not declared in the HTML). Is there a way to verify the existence of a component? ...

Discovering the generic type from an optional parameter within a constructor

Looking to implement an optional parameter within a constructor, where the type is automatically determined based on the property's type. However, when no argument is provided, TypeScript defaults to the type "unknown" rather than inferring it as "und ...

What are the steps for adding an audio file to Firebase Storage?

I'm currently attempting to upload an audio file to Firebase Storage within my Ionic2 project. Initially, I successfully recorded the audio file using the Media plugin (Cordova plugin), and it is playing back correctly from both Android storage and t ...

Using JavaScript, import the variable module object from a specific module

Is there a way to import a module object from a module if I am unsure of the specific objects I will need beforehand? How can I utilize a variable in place of fixed module names? import { dynamicVariable } from './module' The variable represents ...

update-post-thumbnail wp-ajax return false

I have been attempting to utilize the media manager within Wordpress. I am using the post editor outside of the admin area, allowing users to create posts with a featured image. I have used the _wp_post_thumbnail_html function to display the image or provi ...

Unable to show the name of the chosen file

After customizing the input [type = file], I successfully transformed it into a button with a vibrant green background. Here is the code snippet that enabled this transformation: <style> #file { height:0px; opacity:0; } ...