1

I have 3 div element with same class in a HTML code as:

<div class="hide">
</div>

<div class="hide">
</div>

<div class="hide">
</div>

In jQuery I can hide all the div in only one code statement: $(".hide").hide();. How we can hide all the div in single code statement in angular js?

lin
  • 17,956
  • 4
  • 59
  • 83
user2999294
  • 51
  • 1
  • 10

2 Answers2

0

You could so something like this (mixing AngularJS/jQuery):

var results = $document[0].getElementsByClassName("hide");
angular.forEach(results, function(result) {
    var wrappedResult = angular.element(result);
    wrappedResult.hide();
});

However, mixing jQuery into AngularJS application is typically frowned upon, and this just looks like really dirty code that I wouldn't want in a production app.

The best approach and the "Angular" way to do it would be to just wrap your multiple <div>s with an outer <div> and use ng-show/ng-hide.

<div ng-hide="someTrueVariable">
    <div class="hide"></div>

    <div class="hide"></div>

    <div class="hide"></div>
</div>

If you are coming from a jQuery background and are moving into AngularJS, I would highly suggest you take a look at the following Stack Overflow thread. I really think this will help put you into an AngularJS development mindset: "Thinking in AngularJS" if I have a jQuery background?

Community
  • 1
  • 1
Ben
  • 2,441
  • 1
  • 12
  • 16
  • Hence the "_could_" followed by the "Angular" way to do it to demonstrate why you don't want to think like a jQuery developer when working within AngularJS. – Ben Apr 03 '17 at 17:54
0

Put class of element in the attribute hide-element;

HTML :

<div hide-element="hide" class="hide">
    hide1
  </div>  
  <div hide-element="hide">
    hide2
  </div>
  <div hide-element="hide" class="hide">
    hide3
  </div>

JS :

Use hideElement attribute to get class name and hide those element having this class

.directive('hideElement', function() {

    return {  
      restrict: 'A',
      scope: {
        hideElement: '@'
      },
      link: function(scope, ele, attr) {

        var className = scope.hideElement;
        ele.bind('click', function($event) {

          angular.element(document.querySelectorAll("." + className))
            .css('display', 'none');
        })
      }
    }
  })

Working demo plunker

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53