What is the angular way of hiding all specific divs with the same class

元气小坏坏 提交于 2019-12-24 03:00:34

问题


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



来源:https://stackoverflow.com/questions/27639780/what-is-the-angular-way-of-hiding-all-specific-divs-with-the-same-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!