如何编写指令来隐藏div点击页面上的任何位置?

时间:2015-07-20 07:59:22

标签: angularjs

这是我第一次写指令。我正在尝试写指令来隐藏我的div。这是我的HTML:

<div id="loggedIn" close-logged-in class="fade-show-hide"  ng-show="loggedInOpened" ng-cloak>
@Html.Partial("~/Views/Shared/_LoggedInPartial.cshtml")
</div>

我找到了元素但是当我点击页面上的任何地方时我都没有得到任何东西。可以有人帮我如何编写指令,以便当显示用户点击页面上的任何地方时,它会隐藏div.Any建议吗?

'use strict';
    angular.module("accountModule").directive('closeLoggedIn', function () {
        return {
            scope: {},
            restrict: 'A',
            link: function (scope, element, attrs) {

                var loggedIn = angular.element(document.getElementById("loggedIn"));
                console.log(loggedIn);

                var isClosed = false;

                loggedIn.on('click', function (e) {

                    console.log("LOGGED IN ON CLICK ", loggedIn);

                });
            }
        }

我没有收到此消息“登录点击”

1 个答案:

答案 0 :(得分:3)

您不需要getElementById("loggedIn") <div>已作为链接函数中的element参数存在。很少需要通过Angular中的ID来引用元素。

这是你想要达到的目标吗?

DEMO

<强> HTML

<div hide-when-click-anywhere default-display='block'>Click anywhere to hide me</div>

<强> JS

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

app.controller('MainCtrl', function($scope, $window) {
  $scope.isHidden = false;
});

app
.directive('hideWhenClickAnywhere', function ($window) {
  return {

    // bind a local scope (i.e. on link function scope) property 
    // to the value of default-display attribute in our target <div>.
    scope: {
      defaultDisplay: '@'
    },

    restrict: 'A',

    link: function (scope, element, attrs) {

      var el = element[0];

      // set default css display value. Use 'block' if 
      // the default-display attribute is undefined
      el.style.display = scope.defaultDisplay || 'block';  

      angular.element($window).bind('click', function(){

        // Toggle display value.
        // If you just want to hide the element and
        // that's it then remove this if block
        if(el.style.display === 'none'){
          el.style.display = scope.defaultDisplay || 'block';  
          return;
        }

        el.style.display = 'none';

      });
    } 

  };

});

<强>更新

在阅读完评论之后,我认为这可能更符合您的目标;

请注意 template.html 中定义的<button>元素中的这一行:

ng-click="contentHidden = !contentHidden; $event.stopPropagation();"

$event.stopPropagation()阻止事件冒泡并触发我们在指令中$window上定义的“click”侦听器。

DEMO2

<强> app.js

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

app.controller('MainCtrl', function($scope, $window) {
  $scope.hideOnStart = true;
});

app
.directive('panel', function ($window) {
  return {

    scope: {
      // this creates a new 'isolate' scope
      // '=' sets two-way binding between the directive 
      // scope and the parent scope
      // read more here https://docs.angularjs.org/api/ng/service/$compile
      hideOnStart: '=',
      panelTitle: '@'
    },

    transclude: true,
    templateUrl: 'template.html',

    restrict: 'E',

    link: function (scope, element, attrs) { 

      console.log(scope.panelTitle)

      // div content is hidden on start
      scope.contentHidden = scope.hideOnStart || false;

      angular.element($window).bind('click', function(e){

        // check if the content is already hidden
        // if true then ignore
        // if false hide the content
        if(!scope.contentHidden){
          scope.contentHidden = true;

          // we have to manually update the scope
          // because Angular does not know about this event
          scope.$digest();
        }

      });
    } 

  };

});

<强> template.html

<div class="panel panel-default">

  <div class="panel-heading">

    <div class="panel-title">{{panelTitle}}
      <button 
        type="button" 
        class="close" 
        ng-click="contentHidden = !contentHidden; $event.stopPropagation();"
        aria-label="Close"
      >
        <span ng-hide="contentHidden">close</span>
        <span ng-hide="!contentHidden">open</span>
      </button>
    </div>

  </div>

  <div class="panel-body" ng-hide="contentHidden"  ng-transclude></div>

</div>

<强>的index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl"> 

    <div class="container">
      <h1>Demo</h1>
      <div class="row">
        <div class="col-sm-6">
          <panel panel-title="Title" hide-on-start="hideOnStart">
            <h4>Content...</h4>
            <p>foo bar baz</p>
          </panel>
        </div>
      </div>
    </div>

  </body>

</html>