Simple trick to automatically hide the div in AngularJS when clicking outside of it

I want to hide my div for notifications when clicked outside of it. Here is the plunker code link containing the HTML code:

<div ng-hide="notification" ng-click="notifications($event);"><i class="fa fa-bell" aria-hidden="true"></i></div>
<div ng-hide="notifyData">
    <ul>
        <li ng-repeat="noti in newNotificationarray">
            <div class="notifymsg">{{noti.msg}}</div>
            <div class="notifytitle">
                <a href="#">{{noti.title}}</a>
            </div>
            <div class="notifyName">{{noti.cName}}</div>
        </li>
    </ul>                                
</div>

And here is the JS code in the controller:

$scope.notifications=function(event){
    $scope.notifyData=!($scope.notifyData);          
    event.stopPropagation();
};

window.onclick = function(){
    if ($scope.notifyData) {
        $scope.notifyData=false;          
        $scope.$apply();
    }
};

If I do not use "event.stopPropagation();", the div will hide when clicked anywhere on the screen, including the notification div.

Answer №1

To start, the window service needs to be injected into your code. This ensures that it can easily be mocked when running tests.

Additionally, make sure to modify the onclick handler logic for window.

var app = angular.module("myapp", []);
app.controller('mycontroller', ['$scope', '$window', function($scope, $window) {
  ...
  $window.onclick = function(event) {
    if (!$scope.notifyData) {
      $scope.notifyData = true;
      $scope.$apply();
    }
  }
}]);

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 identify this particular method of filtering by multiple attributes? (refer to screenshot)

There is a fantastic filtering mechanism used in the AWS console that allows users to filter on multiple attributes. Does anyone know the name of this feature? Also, are there any similar implementations in Angular? Check out these images for reference: I ...

ng-repeat does not show any blank entries in table

When using ng-repeat to generate a table, I encountered an issue with empty fields being filtered out by AngularJS. Is there a way to display these empty fields as well? Here is an example for reference. `<tr> <td>{{ Ratios['A'] | c ...

Creating an API with an empty body using Express and Node.js

Currently, I am working on creating an API using Express in Node.js. The primary objective of this API is to receive a request containing a photo and then upload that photo to Firebase storage. However, I am facing a challenge where the body of the reque ...

Looking for a way to implement a vertical autoscroll <ul> list that responds to mouse movement using JavaScript and jQuery

Could you assist me in enabling the list items to be moved using mouse movement? When the user moves the mouse cursor vertically upward over the list, the list should scroll downward. If the user moves the mouse cursor downward over the list, the list shou ...

Changes in vertical position of link icon within div based on the browser and operating system

Trying to design a straightforward 3-line mobile menu dropdown, but encountering inconsistency in appearance across different devices. The vertical positioning of the icon is varying based on the operating system and browser version: Linux -desktop Fire ...

Utilize Bootstrap to stylishly fill in gaps within your

I am facing an issue with some simple code: <div class="wrapper_big"> <div class="row-fluid grey"> <div class="span4">Logo goes here</div> <div class="span8">Menu goes here</div> </div> </div> Along with th ...

The tilesloaded event in google.maps.event.addListener is unexpectedly failing to trigger

Today, while testing popover messages on my cordova/ionic app, I compiled the app and noticed that the maps weren't loading. Instead, only my custom "Loading map..." spinning icon kept showing. Upon investigating further, I found that var setMap = n ...

What is the implementation approach for mouseover delegation in pure JavaScript?

How can I successfully apply event delegation for the mouseenter event? I've been searching for a way to achieve what this jQuery code does, but I'm struggling to grasp how it works internally: $(document).on('mouseenter', '.demo ...

Tips for using MatTableDataSource in a custom Thingsboard widget

After creating multiple custom Thingsboard widgets, I've discovered that I can access a significant portion of @angular/material within my widget code. While I have successfully implemented mat-table, I now want to incorporate pagination, filtering, a ...

Is there a way to align the Material UI mobile menu to the left edge of the screen?

Need help with this UI issue: Currently working on designing a mobile web app using React and Material UI. I'm struggling to get the sidebar menu to start from the left edge of the screen, as it seems to have an unwanted margin preventing it. Any sug ...

Looking for the time trigger feature in jQuery using typeahead search?

Is there a way to trigger an event every 3 seconds in Laravel Vue.js? I am currently using jQuery in my script. The issue is that when I type something in the search input field, the event is triggered after each character I type. What I want is for the ev ...

Stunning slide-in and slide-out animation when transitioning between AngularJS states

When creating a single page application, I wanted to implement a slide-right effect for new pages and a slide-left effect for old pages when the user clicks on a button. To achieve this, I referred to a helpful resource () that demonstrated applying CSS cl ...

angularjs ngmodel directive with dual values

I need help with customizing my dropdown control <div ng-repeat="prop in props" style="margin-bottom: 10px;"> <label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.Value}})</label> <div class="col-md-8"> < ...

Can a click event be implemented onto the controls of the anything slider?

Currently, on my website, I am utilizing the Anything slider and would like to implement a click event for the controls. However, I have encountered an issue as my event does not seem to trigger properly. Does anyone have any suggestions or ideas on how to ...

"Test your Knowledge" - Interactive Quiz with PHP and MySQL

After spending the last two days working on this project, I find myself stuck with some messy and confusing code. Despite searching through countless resources for explanations, I still haven't been able to find a solution. The task at hand is buildi ...

Is there a way to display the specific information of a flatlist item in a pop-up window?

Welcome to the HomesScreen.js! This section handles rendering the flat list elements. import { StatusBar } from 'expo-status-bar'; import { Button, Image, Modal, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import { ...

Tips for resolving the error "Cannot access the title property of undefined" when utilizing NextJS prerendering

I am preparing this page in advance for a specific post within my Next.js application: import Head from 'next/head'; import Link from 'next/link'; import client from '../../lib/apollo/client' import POSTS_WITH_SLUGS from &apos ...

Use jQuery to switch the class of the designated DIV in the showcasing slider

Check out this jQuery slider example where I have two Divs - DIV ONE and DIV TWO. Can you help me figure out how to: 1) Automatically change the class of DIV ONE from "test" to "testc" when Slide 1 is displayed by the slider. 2) Automatically update DIV ...

Leveraging the Angular (2) routerLinkActive directive to handle dynamic routes

Although my current approach works, I believe there may be a more efficient way to implement this in Angular. The situation is as follows: Imagine nested, inflected paths like /logos and /logo/:id The markup below functions as intended: <li class ...

How do I get rid of the form border and shadow on my WordPress login page?

Currently revamping the appearance of the Wordpress login page and most aspects are coming together smoothly. I opted to utilize a separate css file for this project, which has been effective overall. However, one issue persists. I've encountered diff ...