Angular.js closing with click anywhere but on the element

前端 未结 1 356
温柔的废话
温柔的废话 2021-01-01 05:11

It\'s pretty common thing, like if you click on inbox here here on stackoverflow. I\'ll be calling that dialog or whatever gets opened a thing.

Now there a

相关标签:
1条回答
  • 2021-01-01 05:24

    The way I've tackled things like this before is using inheritedData to communicate to the click handler whether it's in or out of the thing:

    • In the custom directive for the thing, add a data variable to the element, using jqLite data, say element.data('myThing',true) . If you want to distinguish between multiple instances of the the thing, you might need to use some uniquely generated key.

    • In the same custom directive, in a click event handler on document.body, you can check angular.element(event.target).inheritedData('myThing')

    An example directive that uses this technique is below

    app.directive('thing', function($document,$window) {
      return {
        restrict: 'E',
        template: '<div><span>Inner thing</span></div>',
        replace: true,
        link: function(scope,element) {
          element.data('thing',true);
    
          angular.element($document[0].body).on('click',function(e) {
            var inThing =  angular.element(e.target).inheritedData('thing');
            if (inThing) {
              $window.alert('in');
            } else {
              $window.alert('out');
            }
          })
        }
      }
    });
    

    and can be seen in this Plunker http://plnkr.co/edit/bRDLcLoesM7Z0BIxKxYu?p=preview

    0 讨论(0)
提交回复
热议问题