AngularJS hide any parent div using ng

I already know about ng-if and ng-show methods of showing/hiding DOM elements. In this case, however, I have about 100 div elements, each with multiple child span elements, and whenever a span is clicked, I want the parent div to hide.

Example:

<div>Display text
<span ng-click="hideThisDiv(this)">Option1</span>
<span ng-click="hideThisDiv(this)">Option2</span>
<span ng-click="hideThisDiv(this)">Option3</span>
</div>

In the function, I want to be able to do something like:

$scope.hideThisDiv = function(element){
element.$parent.$id.visible = false;
}

Using console.log(element.$parent) in this function shows, however, that there isn't a simple way to access a "visible" property of this div element. At least, not that I can see so far.

This seems like a simple concept, I'm just lacking the proper syntax or access method.


尝试下面的代码它的作品

var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
  $scope.hideParent = function (event) {
    var pEle = event.currentTarget.parentElement;
    pEle.style.visibility = "hidden";
  }
});
<!DOCTYPE html>
<html ng-app="myApp">
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
	<body ng-controller="MainCtrl">
	  <div>
        This is parent div click below to hide <br />
    <span ng-click="hideParent($event)">Click here to hide</span> <br />
    <span ng-click="hideParent($event)">or Here</span><br />
    <span ng-click="hideParent($event)">or Here</span>
  </div>
			
	</body>
</html>

If you prefer to do this with jquery then use the jqLite approach with angular.element like this:

$scope.hideThisDiv = function(el) {
  angular.element(el.target).parent().addClass('hidden');
};

Then pass in the event like this:

<span ng-click="hideThisDiv($event)">Option1</span>

The add this to your css

.hidden {
  display:none
}  

Solution:

The better approach is to create a custom directive and hide the parent element using jqLite.

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

app.directive('hideParentOnClick', function () {
  return {
    link: function (scope, element) {
      element.on('click', function () {
        element.parent().css({display: 'none'});
      });
    }
  }
});

And in your HTML:

<div>
    Display text
    <span hide-parent-on-click>Option1</span>
    <span hide-parent-on-click>Option2</span>
    <span hide-parent-on-click>Option3</span>
</div>

Plunker Example

Advantages:

  • You can combine this directive with the aforementioned ng-click because the last one is not utilized in this method and can be freely used for any other purpose.
  • Directives are intended for DOM manipulations, not controllers. Read more here.
  • Better overall modularity.
  • 链接地址: http://www.djcxy.com/p/95242.html

    上一篇: 有没有一种“简洁”的方式在JavaScript中进行命名空间?

    下一篇: AngularJS使用ng隐藏任何父div