What is the angular way of hiding all specific div

2019-07-19 23:00发布

问题:

I want to do a simple thing:

I have an app, which has certain divs that in need to show (Only the specific one) and hide if clicked somewhere outside of it (All with the specific class for example).

This is easy using jquery:

$('some-class').style('display','none') //psuedo code here

How should i do the same with angular js?

A specific reason to do so:

I want to build a simple select drop-down (I don't want to use one that exist, i want to understand this...), when i click one, it suppose to open a div right beneath the button, when i click outside of it, it suppose to close not only this one, but some other elements like it in the app.

one point worth mentioning: Not all my select boxes are pre-rendered, some are dynamically added (inside directive), so not all of the are in the $scope, but inside them directives which has isolated scope.

回答1:

Its better to make directives for these kind of things:

Make a directive for toggleDisplay as following

app.directive('toggleDisplay', function() {
  return function(scope, element) {
    element.bind('click', function() {
     element.toggleClass('unneeded-class'); // or something else
    });
  };
});

and then you can apply this directive to any element in the html:

<div toggle-display></div>

You can make a drop down logic or kindof accordion etc following this pattern

How do i listen to a click anywhere in the app, that when i click it and "that" element is not the select box, close all the select boxes?

let suppose you have that opend/dispalyed div that you want to hide when you click outside of it . give it a class "divvy" and attach the following directive to its wrapping container:

 app.directive('toggleFocus', function() {
      return function(scope, element) {
        element.bind('click', function() {
         if(!element.hasClass('divvy'))
         angular.element(document.querySelector('.divvy')).css({display:'none'}) 
        });
      };
    });

html:

<div toggle-focus>
   <div class="divvy"></div>
</div>


回答2:

It's in the angular documentation: https://docs.angularjs.org/api/ng/directive/ngShow

<!-- when $scope.myValue is truthy (element is visible) -->
<div ng-show="myValue"></div>

<!-- when $scope.myValue is falsy (element is hidden) -->
<div ng-show="myValue" class="ng-hide"></div>

just attach ng-show="whateverValue" to each div you want to hide/show based on whether "whateverValue" is true/false