Detecting when a directive element has not been clicked in Angular may involve checking for certain event behaviors

I am looking to enhance the functionality of the "deselect" feature in multiple directives like buttons and popovers. Specifically, I want my functions to activate when the user clicks on an element that is not part of the directive template. Currently, I am utilizing the following JQuery code:

$('body').click(function(evt){
  if($(evt.target).closest($('#directive1')).length == 0 ){
    //deselects first directive
  }

  if($(evt.target).closest($('#directive2')).length == 0 ){
    //deselects second directive
  }

})

Is there a more efficient method to achieve this using Angular?

Answer №1

A straightforward method that recognizes clicks outside a specified element (without using jQuery):

http://jsbin.com/wimeyoruxo/2/edit

app.directive('onDeselect', [ '$document', function($document) {

  return {
    scope: { onDeselect: '&' },
    link: function(scope, element, attrs) {

      var clickHandler = function(e) {

        // Confirm if the target is our element or its descendants
        var target = e.target;
        while (target) {
          if (element[0] === target) return;
          target = target.parentElement;
        }

        // Execute the function
        scope.$apply(function() {
          scope.onDeselect({$event:e});
        });
      };

      $document.on('click', clickHandler);

      // Remove handler upon destruction
      scope.$on('$destroy', function() {
        $document.off('click', clickHandler);
      });
    }
  };
}]);

Implementation example:

<div on-deselect="doSomething($event)"></div>

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

CodeIgniter session automatically expires problem

I am experiencing automatic logout on my website. How can I resolve this issue? Here are the configuration variables for my site, and the CodeIgniter version is 2.2.0 $config['sess_cookie_name'] = 'ci_session'; $config['sess_ ...

Retrieving data from an Ajax POST request URL

I am currently working on a project where I need to extract the URL of a POST request made through AJAX. My router is set up to handle all user requests, including GET and POST methods. However, I am struggling to identify the specific URL being used in th ...

What is the method for sending an AJAX request with a dynamically looping ID number parameter in the URL

I am looking to make multiple AJAX calls with a loop parameter named [id] in the URL, starting from request.php?id=1 and ending at id=9. I want to send each call after a 3-second delay. As a JavaScript beginner, I'm unsure of where to begin implementi ...

Unusual conduct exhibited by jQuery's css() function for setting the width

My goal is to retrieve the width of the initial .imagen element and apply it to the img within .imagen. HTML: <div class="imagen"> <div class="normal"> <img> </div> <div class="hover"> <img> ...

Using the AngularJS double Array ng-repeat feature allows for easy iteration

I am in the process of developing a web application using AngularJS. My goal is to: Display both sets of arrays in one list using ng-repeat and eliminate any null values. For example, Value One A, Value One B, Value Two A, Value Two B Issues I am fa ...

Tips for integrating the AJAX response into a Sumo Select dropdown menu

I am currently using Sumoselect for my dropdowns, which can be found at . The dropdowns on my page are named as countries, state, and cities. The countries are shown in the dropdown, and based on the country selected, the corresponding state name should a ...

It's impossible to remove a dynamically added class from a button

I'm facing an issue with adding and removing classes from a button using jQuery. I added a new class to the button, then removed it, but now when I click the button again I want to revert back to the initial class. Unfortunately, my code is not workin ...

Unable to retrieve the value of $parent in the ng-included controller

As a beginner in Angular, I am currently working on developing an application. To include my view based on the value of the "currentURL" variable in my main controller, I utilize the "ng-include" directive. However, when attempting to access the main cont ...

I possess a pair of UI tabs. Whenever a button located outside the tab is clicked, I am required to activate a distinct tab

As a beginner in Javascript, I recently encountered an issue with a UI tab element that contains two tabs. My goal is to create a button that, when clicked, will scroll up and activate the second tab. <style> .tab-container { overflow-x: ...

"Utilizing jQuery to apply a class based on the attributes of CSS

Is there a way in jQuery (or plain JS) to create a condition based on whether a div has a specific CSS attribute? For instance, I need jQuery to apply position:fixed to an element's CSS when another element has display:none, but switch back to positi ...

Experiment with AngularJS and Jasmine by utilizing the stand-alone command line interface for testing

I have been working on a basic .js file and testing it with Jasmine. The tests run smoothly when using Jasmine's SpecRunner.html. However, I was wondering if it is possible to achieve the same results through a command line interface. I do have node ...

No data stored in Angular service array

I am facing an issue with storing JSON data in a shared array within a service. The problem arises when I try to update the array with new content, as it seems that clearing the array before loading new data doesn't work properly. Here is how my serv ...

absence of data returned in Ajax call for a REST endpoint

Currently, I am testing a straightforward REST service that was created using Java. The server-side code includes: import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import ...

Angularjs still facing the routing issue with the hashtag symbol '#' in the URL

I have recently made changes to my index.html file and updated $locationProvider in my app.js. After clicking on the button, I noticed that it correctly routes me to localhost:20498/register. However, when manually entering this URL, I still encounter a 4 ...

Convert less to CSS using the less.modifyVars() function along with Angular

I've created a list of inputs using the following code: <div ng-controller="MainCtrl"> <div ng-repeat="variable in variables"> <label>{{ variable.slug }}</label> <input type="text" ng-model="variable.value" ng-chang ...

Using a combination of PHP and JQuery, I noticed that adding an IF statement within the document ready function

In the (document).ready function, the code below is used to properly display the order form: <?php if (isset($_POST['preview-order'])) { //IF PREVIEW FORM ?> $("#cam-order-preview").show('slow'); <?ph ...

I am looking to split an array into smaller subarrays, each containing 5 elements, and assign a distinct class to the elements within each subarray. How can I

I have a group of "n" "li" elements that I would like to split into "x" subsets using jQuery. Each subset should contain 5 "li" elements, and I also want to assign a different class to each subset. <ul> <li>text1</li> <li>text2&l ...

Attempting to conceal image previews while incorporating pagination in Jquery

I'm working on implementing pagination at the bottom of a gallery page, allowing users to navigate between groups of thumbnail images. On this page, users can click on thumbnails on the left to view corresponding slideshows on the right. HTML <di ...

Can an iFrame be programmed to automatically scroll?

Here's an example of autoscroll: I am looking to implement autoscroll for the content within an iframe that has a width wider than the browser window. Can this be achieved using jQuery? ...

Change the ng-model of the initial controller when a button is clicked in a separate controller

I am working on an AngularJS application that has two controllers. I am facing an issue where I need to update the ng-model of an input field in the first controller by clicking a button in the second controller. Accessing the $scope of the first controlle ...