Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html ng-app="app">
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script src="https://code.angularjs.org/1.3.2/angular.js"></script>
  </head>
  <body>
    <div ng-init="d1.click = 0" on-deselect="d1.click = d1.click + 1">
      <h1>DIV 1 <i>(clicks outside: {{ d1.click }})</i></h1>
      <button>Click</button>
    </div>
    <div ng-init="d2.click = 0" on-deselect="d2.click = d2.click + 1">
      <h1>DIV 2 <i>(clicks outside: {{ d2.click }})</i></h1>
      <button>click</button>
    </div>
  </body>
</html>
 
body {
  text-align: center;
}
button {
  padding: 5px;
  font-size: 20px;
}
div {
  padding: 20px;
  margin: 20px;
  outline: 4px solid gray;
}
div:nth-child(1) {
  color: red;
  background-color: lightgreen;
}
div:nth-child(2) {
  color: white;
  background-color: red
}
 
var app = angular.module('app', []);
app.directive('onDeselect', [ '$document', function($document) {
  
  return {
    scope: { onDeselect: '&' },
    link: function(scope, element, attrs) {
      var clickHandler = function(e) {
        var target = e.target;
        while (target) {
          if (element[0] === target) return;
          target = target.parentElement;
        }
        
        scope.$apply(function() {
          scope.onDeselect({$event:e});
        });
      };
      $document.on('click', clickHandler);
      // clean handler on destroy
      scope.$on('$destroy', function() {
        $document.off('click', clickHandler);
      });
    }
  };
}]);
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers