What is the best way to utilize $(target) within a directive?

I created a custom directive for selecting time using two blocks. The challenge is detecting the target event on specific blocks within the directive's template. Directive Template:

<div class='time-picker-container'>
    <div class='block1' ng-click='show()'>1</div>
    <div class='block2' ng-show='selectVisible'>2</div>
</div>

JS:

scope.selectVisible = false;
scope.show = function() {
    scope.selectVisible = !scope.selectVisible;
}
$rootScope.$on('documentClicked', function(inner, target) {
    // attempting to hide div.block2 if the user clicks outside the block
});

Main concept: when the user clicks on the document, outside of div.block2, the block disappears. If the user clicks inside div.block2, the block remains visible.

Function execution:

angular.element(document).on('click', function(e) {
        $rootScope.$broadcast('documentClicked', angular.element(e.target));
    });

Answer №1

Make sure to include $event as an argument in your template's ng-click handler function.

<div class='time-picker-container'>
    <div class='block1' ng-click='show($event)'>1</div>
    <div class='block2' ng-show='selectVisible'>2</div>
</div>

In the ng-click handler, use stopPropagation() to prevent the execution of the outsideClickHandler.

angular.module("myApp").controller("myVm", function($scope, $document) {
    var vm = $scope;
    vm.selectVisible = false;

    vm.show = function(event) {
       console.log("inside click");
       event.stopPropagation();
       vm.selectVisible = vm.selectVisible ? false : true;
    }

    function outsideClickHandler(e) {
        console.log("outside click");
        $scope.$apply("selectVisible = false");
    }
    $document.on("click", outsideClickHandler);

    $scope.$on("destroy", function() {
        $document.off("click", outsideClickHandler)
    })
})

Ensure that you remove the $document click handler when the scope is destroyed to avoid memory leaks.

Check out the DEMO on JSFiddle.

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

Navigating between Vue Router pages triggers multiple events within the mounted() lifecycle of VueJS

Currently, I am immersed in a project using Electron with a Vue CLI setup and the Vue CLI Plugin Electron Builder. The overall functionality is working perfectly fine except for a peculiar bug that has recently surfaced. The issue arises when navigating b ...

Choose a sibling element using CSS styling

As I'm developing an AngularJS component, I am on the quest to identify ANY sibling of a particular tag, irrespective of whether they are div, span, or p. I'm hoping for a CSS-native solution that resembles something along the lines of div:siblin ...

Update the image within the svg tag

I am attempting to modify a preexisting SVG element within an HTML document. Here is the current code: <svg class="logo" viewBox="0 0 435 67"> <!-- IMAGE DIMENSIONS --> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#logo- ...

Looking for a new slider option to replace the traditional Conveyor belt slideshow?

I have successfully used the Conveyor belt slideshow script from http://www.dynamicdrive.com/dynamicindex14/leftrightslide.htm. Now, I am looking to find another script that works similar to this one. Does anyone have any recommendations for a tool that ...

Display array values in JavaScript from different arrays

I'm currently working on extracting data from my API to plot it in a graph. Specifically, I am interested in obtaining an array that contains only the 'date' values. Here's what I have managed to extract so far: This is the code snippe ...

Unable to trigger click event

I apologize for asking the same question again, but I'm really struggling with this seemingly easy (or difficult?) code problem. Despite trying out Rory McCrossan's solution from here, it still doesn't seem to work for me. Can someone please ...

Click the toggle ng-press attribute

I have a section with an on-click="..." action. The event slightly adjusts the section's appearance within the document so that it resembles a button. I am looking to switch between making this section clickable and non-clickable in my program. While ...

Looping through items using ng-repeat according to the chosen option in a select dropdown

After expanding my project, I encountered an issue with the main object structure: { screens: [{ id: 0, name: 'Screen0', sections: [{ id: 0, sectionItems: [] }, { id: 1, sectionItems: [] }, { i ...

The children's className attribute can impact the parent element

As I work on creating a card object, I envision it with the className .card that is styled in CSS as follows: .card img{position:absolute; width:150px; height:160px} I want only the images inside my div to overlap each other while not affecting the divs ...

How to integrate an AngularJS page into a Node application

Exploring the realm of single page web apps with node, angular, and jade has been an interesting journey for me as a newcomer to angular. I am currently faced with a dilemma regarding my app.js file - how can I ensure that my initial page template loads fr ...

Is there a way to disable automatic spacing in VS code for a React file?

I am currently working on my code in VS Code within my JSX file, but I keep encountering an error. The issue seems to be that the closing tag < /h1> is not being recognized. I have attempted multiple methods to prevent this automatic spacing, but so ...

Issue with React occurring when attempting to delete an input component

I seem to be facing a challenge that I can't quite figure out whether it's related to React or not. To help illustrate the issue, I've created a simple example outside of my project: https://codepen.io/as3script/pen/VMbNdz?editors=1111 Wit ...

The text is not displaying as expected due to a timeout issue

Trying to create a pop-up that functions as follows: After 3 seconds, the close button should appear, but during those 3 seconds, there will be a countdown. However, I'm encountering an issue where no text is being displayed. var n = 3; function p ...

Struggling to align your image properly?

My attempt to center the image "Logo_Home.svg" on my page has failed, as it is currently positioned in the top left corner. Can anyone help me identify what I am doing wrong and guide me in the right direction? Thank you. EDIT 1 I realized that I forgot ...

The Vue.js application appears to be functioning properly with no error messages, however

Currently, I am in the process of learning Vue. Recently, I came across a helpful tutorial that I've been trying to implement using the standard vue-cli webpack template by splitting it into single file components. Despite not encountering any errors ...

You cannot use a relative path when inserting an image tag in React

I am having an issue with my img tag not loading the desired image when using a relative src path in my React project. When I try: //import { ReactComponent } from '*.svg'; import React from 'react'; import firebase from "./firebas ...

Is it possible to obtain the index of a table row using querySelector?

Is it possible to find the rowIndex of the first occurrence of a table row within the #myTable using JavaScript? http://jsfiddle.net/bobbyrne01/fmj6np6m/1/ html .. <table id="otherTable"></table> <table id="myTable"></table> js ...

Implementing setTimeout with the copy button: A guide

How can I implement a setTimeout function in the copy button so that when a user clicks on it, the text will change to "copied" and then revert back to "copy" after 3-4 seconds? Please help me find a solution to this problem and also optimize the JavaScrip ...

Looking to reposition the control buttons above the slider in easySlider 1.7?

I am thoroughly enjoying the easySlider 1.7 and found it incredibly simple to implement. The only modification I wish to make is to relocate the next and previous buttons above the slider instead of below it. Does anyone have any suggestions on how to achi ...

C# web service is unable to return a specific value

I attempted to use a basic web service (just to test if the value will populate in the JavaScript code). I experimented with a very simple snippet, but it kept returning 'undefined'. Can you offer some guidance? I have tried several solutions wit ...