Personalized Angular dropdown menu

Recently, I've started delving into angularJS and I'm eager to create dropdowns and tabs using both bootstrap and angular. Although there is a comprehensive angular bootstrap library available, I prefer not to use it in order to gain a deeper understanding of the underlying mechanisms. However, I've encountered some difficulties while attempting to develop the necessary dropdown functionality. The issue at hand is:

  1. I find that I have to click on the dropdown to close it if it's already open. Ideally, I would like to be able to close it by clicking or tapping anywhere outside of the dropdown.

I've created a pen showcasing my current markup and functionality: http://codepen.io/anon/pen/EBwlA

This happens to be my initial angular project; hence, if any aspect seems off-base or could be improved upon, please don't hesitate to provide feedback :)

Many thanks!

Answer №1

To enable collapsible functionality, simply add an ng-click event to each li or a tag with the following code:

 ng-click="toggleOpen($event)"

If you have a specific method in mind that you'd like to explore, feel free to let me know.

This approach involves using a service to facilitate coordination between collapsible elements:

app.service('collapsables',['$rootScope',function($rootScope){ return{ notify:function(event,payload){ $rootScope.$broadcast(event,payload); } } }]);

app.directive('collapsable',['collapsables',function(collapsables){
    return{
        restrict:'A',
        controller:function($scope){
            $scope.Toggle=function(){
                 $scope.expanded=!$scope.expanded;
                 collapsables.notify('toggled',{scid:$scope.$id,group:group});
             }
             $scope.$on('toggled',function($event,details){
                     var canClose=(!$scope.group || $scope.group==details.group || !details.group) && $scope.$id!=details.scid && $scope.expanded 
                     $scope.expanded=canClose.
              })
         }
}



}])

By attaching the collapsable directive to any element, you can facilitate communication between collapsibles and even group them for isolated behaviors. It's important to note that this directive doesn't create a new scope but enhances the existing one to include behavior. However, if multiple instances exist within the same controller, consider implementing a variant using isolated scopes for better organization while maintaining the core concept.

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 are the steps for transitioning an Angular application from MonoRepo to PolyRepo?

Having created three separate Angular applications with individual workspaces, projects, and repositories, I am able to share modules among them using @angular-architects/module-federation. However, I am facing challenges when it comes to sharing component ...

Previewing an uploaded image before submitting with FileBase64: A step-by-step guide

How can I implement a preview for an uploaded image before submitting the form? I have the upload functionality working but I would like to add a preview feature for the image. Below is the code snippet I am currently using: const [shop, setShop] = us ...

Express landing page continuously serves static files

I'm facing an issue with using static files in my project. When a user makes a get request to the "/" landing page, I intend to send non-static data like a JSON response. However, instead of sending "123", it automatically serves my index.html file fr ...

Is the form data in AngularJS not submitting correctly?

Why is my HTML form data not being submitted using POST method? HTML View Page:- <div class="col-sm-12"> <div class="card-box"> <form class="form-inline" name="addstock" ng-submit="saveStockPurchaseInvoice()"> <h ...

The express js backend (mongodb) is returning {error:{ }}

I'm learning how to POST Data to a Mongo DB using Express.js. Recently, I picked up Express.js for backend server development and this is my app.js const express = require("express"); const mongoose = require("mongoose"); require("dotenv/config") con ...

Issue with vue-router not displaying template for nested routes

My route configuration looks like this: const routes = [{ path: '/', component: Home, children: [ { path: "/health", children: [ { path: 'overview', ...

Configuring a module in AngularJS: step-by-step guide

Having just started learning AngularJS, I feel confident with the basics and now seeking to grasp some best practices. However, as I analyze a code snippet, I find myself encountering certain parts that remain unclear to me: ciApp = angular.module("myApp ...

Having trouble setting the select value with JavaScript in the Selenium web driver

I am working on a web page that includes a cascaded dropdown feature. The data in the second dropdown appears to be generated via ajax based on the selection made in the first dropdown. Here is the code for the first select option: <select class="form- ...

The play button in videojs is unresponsive when incorporated into JavaScript responses

I've been trying to implement a video player using video.js, but I'm running into issues with the play button not responding to my JavaScript code. I have all the necessary scripts included in my file, but I haven't been able to find a solut ...

pop-up window that shows chosen choices using javascript or ajax

I have a specific HTML code that allows users to select multiple options. I would like these selected options to be displayed in a popup or a div in real-time as the user makes their selections. I have attempted using a selectbox with checkboxes, but extra ...

"Ng-repeat function seems to be malfunctioning, although I am able to view

There seems to be an issue with ng-repeat when dealing with an array of objects: dummy.json [ {"name":"alpha", "data":[{"name":"Unit 1", "prereqs":[]}]}, {"name":"beta", "data":[{"name":"Unit 1", "prereqs":[]}]} ] While I am able to fetch the total ...

Tips for updating form values with changing form control names

Here is an example of a form I created: public profileSettingsGroup = new FormGroup({ firstName: new FormControl('Jonathon', Validators.required) }) I also have a method that attempts to set control values in the form: setControlValue(contro ...

Master the art of displaying complete text when zooming in and elegantly truncating it when zooming out

I am currently working on a data visualization project using d3.js. The tree chart that I have created is functioning well, but I would like the text to react dynamically when zooming in and out. You can find the code for my project on this JSFiddle page. ...

Sending a string to an HTTPServlet using jQuery's Ajax method resulted in an empty request

I am currently working on sending data back to my HTTPServlet when a button is pressed. My ultimate goal is to send JSON data, but for now I am just focusing on sending back a simple string. Whenever I click the saveThis button, my server displays "Empty" ...

Unlocking the Power of Javascript Promises in FileReader

I am facing an issue with my code. Here is the HTML snippet: <input type='file' multiple> And this is my JavaScript code: var inputFiles = document.getElementsByTagName("input")[0]; inputFiles.onchange = function(){ var fr = new File ...

Issues encountered with the functionality of face-api and tensorflow.js within the browser

I've been trying to execute this example in the browser Check out the example here Specifically looking at this code snippet <!DOCTYPE html> <html> ... (Contents of the code snippet) ... </body> </html> Unfortunately, I&apos ...

Enrollment of Vue components

After importing the component into the JavaScript file, I added it to the index.vue file as follows: import fmsSubUnitDetails from '../subunitDetails'; export default{ components: { fmsSubUnitDetails }, } Despite this, I am still encount ...

Use JavaScript to upload a JSON file containing arrays into separate tabs

Looking for help with incorporating JSON data into an HTML template that features tabs and a gallery? Take a look at my setup below: <div class="tab"> <button class="tabLinks" onclick="openDiv(event, 'overview'); appendData()" id= ...

Having trouble getting a NodeJS sample app to start up because it can't locate the 'config' file?

I am currently delving into the world of Node.js and have been attempting to launch a sample application that I recently acquired from a git repository: https://github.com/madhums/node-express-mongoose-demo Despite diligently following all the provided i ...

Are you familiar with manipulating Arrays or Objects in jQuery?

In JavaScript, we can create objects with keys as strings for similar functionality to an associate array. Check out this example here. For example: ".home-title":[ ["font-size","12px"], ["line-height","16px"], ], However, if you need a ...