Prevent Event Bubbling in AngularJS

Having trouble implementing stopPropagation while working with multiple drop down menus. I want the menu to toggle off when clicked outside, and only one menu open at a time so that opening another closes the first.

If my approach is wrong, any guidance in the right direction would be appreciated!

Thank you!

This is how I'm currently handling the drop menus:

<a ng-click="popout.isVisible = !popout.isVisible">Drop Menu #1</a>
<ul ng-show="popout.isVisible">
    <li>This is some text.</li>
    <li>This is some text.</li>
    <li>This is some text.</li>
</ul>

<a ng-click="popout.isVisible = !popout.isVisible">Drop Menu #2</a>
<ul ng-show="popout.isVisible">
    <li>This is some text.</li>
    <li>This is some text.</li>
    <li>This is some text.</li>
</ul>

Attempted to use a stopEvent directive found in code, but it's not functioning as needed:

myApp.directive('stopEvent', function () {
  return {
    link: function (scope, element, attr) {
      element.bind(attr.stopEvent, function (e) {
          e.stopPropagation();
          alert('ALERT!');
      });
    }
  };
});

Answer №1

You've mentioned the stopEvent directive in your explanation, but it doesn't seem to be utilized in your HTML code. Below is a basic implementation based on your description:

Check out this example on JSFiddle

HTML

<div ng-app="app" ng-controller="p" ng-click="hideEverything()">

    <a ng-click="popout[0].isVisible = !popout[0].isVisible" stop-event="click">Drop Menu #1</a>
<ul ng-show="popout[0].isVisible" stop-event="click">
    <li>1111</li>
    <li>This is some text.</li>
    <li>This is some text.</li>
</ul>

<a ng-click="popout[1].isVisible = !popout[1].isVisible" stop-event="click">Drop Menu #2</a>
<ul ng-show="popout[1].isVisible" stop-event="click">
    <li>2222</li>
    <li>This is some text.</li>
    <li>This is some text.</li>
</ul>


</div>

JavaScript

function p($scope) {
    $scope.popout = [ {}, {} ];
    $scope.hideEverything = function () {
        alert('hiding');
        $scope.popout[0].isVisible = false;
        $scope.popout[1].isVisible = false;
    };
}

angular
.module('app', [])
.directive('stopEvent', function () {
  return {
    link: function (scope, element, attr) {
      element.bind(attr.stopEvent, function (e) {
          e.stopPropagation();
          alert('ALERT!');
      });
    }
  };
});

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

The ng-model value does not display in Angular 1.4.14 <input> after adding an item in ng-repeat loop

I'm facing an issue with the ng-model in ng-repeat of InvoiceLines: - After adding a new Invoice Line for the first time, I type some characters in the ng-model and the input value displays correctly. The InvoiceLines now has 1 line. - However, af ...

Tips for sending a function in an AJAX request from jQuery to a Node.js server

This is the code I'm working with: let url = "/blabla"; let ajax_options = { data:{ params_list:{ sortFunction: (x, y) => parseFloat(x) - parseFloat(y); } } }; $.ajax(url,ajax_options).then((res) => { //d ...

Using an auxiliary outlet in Angular causes the entire page to refresh

I'm utilizing an auxiliary outlet in my angular project. Within my routing.module.ts, the configuration is as follows: Routing.module.ts const routes: Routes = [ { path: '', component: XXXComponet, }, { ...

Organizing lists with HTML unordered lists

Is it possible to sort list items by numbers within a strong tag using JavaScript code? The current code successfully sorts the numbers, but removes them from the div tag. (The JavaScript code used below is for sorting by Name and works properly when &apos ...

Webpack appears to be failing to render any content on localhost, despite successfully attaching the script tag in the HTML. The homepage is not displaying any information as

I am just starting out with webpack and have created a React application with index.js as the entry file and app.js as the main component being rendered. The webpack builds without any errors, adds the script tag to the HTML file, but strangely does not re ...

Having trouble with the npm Twitter API functionality?

I'm attempting to execute a simple stream using an example code snippet. Here is the code I am working with: var twit = require('twitter'); var twitter = new twit({ consumer_key: '[KEY]', consumer_secret: &ap ...

Highlighted keyword: Unusual mouse movements

I am utilizing the Summernote plugin from Summernote to craft an aesthetically pleasing textarea, and adding the Mark.js plugin from Mark.js to highlight a specified keyword (such as foo) within that textarea. This is the HTML code I have: <div id="te ...

Every time I try to run a basic thread code, it causes the Firefox extension (nsIThread

Whenever I try to create a basic thread in Firefox (Aurora 30), it consistently crashes. The only action it performs is executing the function "task" from the thread. Any thoughts on what could be causing this issue? function task(a, b) { alert(a ...

Error: Invalid character encountered during login script JSON parsing

I found this script online and have been experimenting with it. However, I encountered the following error: SyntaxError: JSON.parse: unexpected character [Break On This Error] var res = JSON.parse(result); The problem lies in the file below as I am unf ...

ensure that html tags display properly when retrieved from json in an angular directive template

Trying to embed ruby tags in a directive template but struggling with escaping them. Despite reading about $sce and filters, the confusion deepens as browser tabs multiply. The directive code is as follows: angular.module("ngFlashCard", ["ngSanitize"]).d ...

What is the best way to assign table rows to various interfaces in typescript?

Assuming I have the interfaces provided below: export interface IUserRow { id: string, state: string, email: string, } export interface ITableRow { id: string, [key: string]: any; } export type Rows = ITableRow | IUserRow; // additio ...

JavaScript's setAttribute function is not functioning as expected

I have been using the setAttribue method as shown below. It works perfectly for the first instance, but after that, when I try to change the value, it displays an alert without updating with document.getElementById("to").setAttribute("value", selValue); d ...

Retrieve the value of a specific key from the previous state object using the useState hook

I've searched exhaustively on stack overflow, but couldn't find a similar solution. I need to update an object key-value pair without using the old value. Let's consider a graph declared using useState: const [graphBounds, setGraphBounds] ...

React components receive props as an empty array when they are being passed to the component

I am passing a state to a component as a prop in the following way: componentDidMount() { axios.get("path/to/data") .then(result => { this.setState({ receivedData: result.data, }); ...

Automatically fill in the Modal popup

Today, I encountered a challenge while trying to keep the current page in a jQuery data table. Clicking on the "Edit" link in a row would open a modal pop-up and fill in the controls. However, this action resulted in a postback that set the page back to pa ...

Enhancing User Interfaces with TypeScript Accordions

Looking for a way to expand the sub-menu when the SETTINGS menu is clicked using typescript. Here is the list structure: <li> <a href="#"> <i class="fa fa-cogs fa-fw"></i> <span>SETTINGS</span> </a> ...

Verify and include phone number entry using Jquery

My input field always requires a + sign to be the first character. HTML <input id="phone"> JS $("#phone").keydown(function (e) { $(this).get(0).value+="+"; // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(e.keyCode, [ ...

State variable fails to maintain its value during onChange event

I'm currently working on implementing a text box in a pop-up window for my application. To allow users to input text, I've utilized a useState variable and update the state with the value of the input during the onChange event. However, I'm ...

Dynamic ng-click button becomes unresponsive after initial click

There is a button within an ng-grid cell that serves to toggle the status between STARTED and STOPPED. The cell configuration is as follows: {field:'status', displayName:'Status', cellTemplate: 'cell/statusCellTemplate.html'} ...

Challenges encountered while formatting Json strings for WCF service transmission

I need assistance in connecting a JavaScript application to a WCF service. The WCF Service I have includes the following method: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFor ...