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

Validating classes in Node.js using class-validator

I'm having some trouble with the class-validator package in my Node project. It's not being recognized and throwing an error. @MinLength(10, { ^ SyntaxError: Invalid or unexpected token Here's an example of what I'm doing: co ...

Identify and emphasize CSS codes within PHP files using Notepad++

I'm working with a PHP file in Notepad++ that correctly highlights PHP code. Within this file, I have JavaScript code which is properly recognized between the <script type="text/javascript"> and </script> tags. However, the CSS code withi ...

method for sorting labels in Select element in ReactJS

Hey there, I'm facing an issue with the code snippet available here. I would really appreciate it if you could assist me in resolving this problem. This is the code: import React from "react"; import { Select } from "antd" ...

Personalizing bootstrap tabs

I'm currently working on a project that requires implementing custom-style tabs. I'm facing challenges in customizing the borders of the tabs, particularly rounding the red bottom border and adding space between the right border and bottom border ...

The feature for choosing rows is not functioning properly when using materializecss in Tabulator

While working on my project, I encountered an issue with selecting rows. After some debugging, it was revealed that the culprit behind this behavior is the tabulator_materialize.min.css file. Interestingly, when I don't use this CSS, everything functi ...

Use the powerful $.post() method to transfer an image to another page seamlessly

I have two pages, the first page contains a form where users can enter information such as name and mobile number. Additionally, they can upload an image. I would like to use jQuery to access the uploaded image and send it to another page using the $.post( ...

Is there a way to modify the rounded corners of a checkbox in material-ui?

After importing material-ui into my react app, I was able to change the color and size of a checkbox as shown. However, I am having trouble changing the icon's border radius. How can I achieve this? import FormGroup from '@mui/materi ...

Guide on integrating HTML from a response into the render function in React JS

I've been doing some research but I'm struggling to find a good solution for this issue. I have a response that looks like this: "name": "another test", "description": "para hacer el aseo", &quo ...

Interactive div with dynamically generated click event

I need to add an onclick event to a button that is being generated dynamically via ajax. How can I achieve this? This is the code responsible for generating the content. When we click on an item, I want a popup window to appear. function retrieveTableDat ...

Tips for implementing filters on `<span>` elements

When I transition from Spring to UI, I encounter the following code: <span th:text="${fromController.number}"/> The "number" mentioned here is a double retrieved from the database. I am looking to filter values into three categories: 0 to 30, 30 to ...

In a Vue Application, the static HTML elements are loaded before fetching data

Utilizing VueJS and VueRouter in my application has presented a challenge. The issue lies in the fact that static HTML elements within the Vue Component load before the data is fetched, resulting in empty forms and tables being displayed initially. I have ...

The issue of JQuery Mobile not recognizing HREF links when combined with Javascript

I am facing a challenge with my button functionality that is supposed to open a panel. However, there seems to be an interference caused by my JavaScript code. The panel contains a notifications center and in order to retrieve the notifications, I have to ...

Making asynchronous requests using AJAX

$.ajax({ async:false, url: "ajax/stop_billed_reservation_delete.php", type: "POST", dataType : "json", data : { "rid" : <?php echo $_GET['reservationId']; ?> }, success: function(result){ ...

How to align CSS counters to the right within the ::before pseudo-element

Utilizing CSS counters and the <code> element to display syntax highlighted code snippets with automatic line numbering: JSFiddle HTML: <code> <div class="line"><span>line 1</span></div> <div class="line">< ...

The removal of classList.remove() only eliminates the class itself, not its contents

My goal is to add one class and remove another class when the start quiz button is clicked. While the 'info_box' class is successfully added, the 'start_btn' class does not get removed; it just changes position (from flex to no flex). T ...

What is the superior method for generating HTML: dynamically via PHP or jQuery AJAX?

Hello, I am seeking advice on the best practice for dynamically generating HTML. There are two methods I am considering: Option 1: Direct PHP <div id='id-here'> <?php $user->id = $_GET['id']; $user-> ...

Observing modifications in the database is possible after executing the setInterval function

I am using a JavaScript function that runs every 4 seconds with setInterval. Once this function is executed for the first time, it calls an ajax request and changes a column value in the database. I want to know how I can check if this value has been succe ...

When attempting to use a value outside of its block, the function may return a

My current task involves querying one collection to retrieve IDs, then using those IDs to query another collection and send back the response. The process runs smoothly until I encounter an issue with retrieving values outside of a block when using forEach ...

No animated scrolling occurring

I have been struggling with this problem for a while now and despite having gone through 100 questions, I still can't find a solution as to why my code snippet is failing. Here is the jQuery code I am using: $("#readmore").click(function(event){ ...

React DnD now enables dragging an entire list of cards instead of just a single card

Implementing react DnD in my react Project has been challenging. In the render method, I have defined a variable called Populate that generates a list of cards as shown below: render() { var isDragging = this.props.isDragging; var connect ...