0

I have created a directive in angularJS which have an HTML table that's need to be hidden in some cases. I want to hide the table when there is a click anywhere on the page but the table itself. I did it like this, I set attribute tabindex (-1) on table then added ng-blur function. Its work fine in chrome and Firefox but i am having an issue with IE 11, when i click on the table it hide itself.

my code:

HTML:

<table id="WizardGrid" tabindex="-1" class="table table-striped table-bordered table-condensed table-hover" ng-blur="vm.onBlur($event)">

controller:

self.onBlur = function ($event) {
            self.showWizardWindow = false;
            console.log($event);
 };

In the end what i want is to focus on the table and on lost focus to hide, when i click on the table (tr, td etc.) to stay in show mode.

yanivz
  • 158
  • 1
  • 13
  • 2
    `ngBlur` probably only applies to [focusable elements](https://stackoverflow.com/a/1600194/1264804). You should probably look into a generic 'click outside' directive. – isherwood May 07 '19 at 14:31

1 Answers1

0

In my opinion ng-blur is not good idea for this case and @isherwood is right!, but we can use custom directives like clickOff for case we need call action on click outside our target, i hope it useful for you my friend.

var app = angular.module("app", []);

app.controller("ctrl", function($scope) {
  $scope.outsideTable = function(){
    console.log("outside table")
  }
  
  $scope.insideTable = function(){
    console.log("inside table")
  }
})


app.directive("clickOff", ["$parse", "$document", function ($parse, $document) {
    var dir = {
        compile: function ($element, attr) {
            // Parse the expression to be executed
            // whenever someone clicks _off_ this element.
            var fn = $parse(attr["clickOff"]);
            return function (scope, element, attr) {
                // add a click handler to the element that
                // stops the event propagation.
                element.bind("click", function (event) {
                    event.stopPropagation();
                });
                angular.element($document[0].body).bind("click", function (event) {
                    scope.$apply(function () {
                        fn(scope, { $event: event });
                    });
                });
            };
        }
    };
    return dir;
}]);
main {
  height: 100vh;
  background: #eee;
}

table {
  width: 100%;
}

table tr td, table tr th {
  border: solid 1px #ccc;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<main ng-app="app" ng-controller="ctrl">

  <table click-off="outsideTable()" ng-click="insideTable()">
      <tr>
        <th>Table</th>
      </tr>
      <tr>
        <td>ngMouseLeave custom directive</td>
      </tr>
  </table>
</main>
Maher
  • 2,517
  • 1
  • 19
  • 32