Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.parents() in Angular?

Is there a way I could emulate jQuery's .parents() method in Angular, without having to actually include jQuery?

The final goal is to get all the parents of a DOM element.

EDIT: Why I need this?

I'm creating a directive (a dropdown-like widget). The dropdown should listen the entire <body> for clicks and close itself (if it's open) if a click is made outside of the widget's area.

Now, I know how to create a simple directive that would listen for mouse events, like this one:

app.directive('mouseTrap', function() {
  return function(scope, elem) {
    elem.bind('click', function(event) {
      scope.$broadcast('click', { event: event } );
    });
  };
});

...which I would then use like this: <body mouse-trap .... > and

$scope.$on('click', function(msg, obj) {
  console.log("click!");
});

That is where I need to check if any of the parents of the clicked object is the top-level div of my widget, and if not, close the widget.

like image 523
alexandernst Avatar asked May 25 '15 16:05

alexandernst


People also ask

How to share data between parent and child components in angular?

A common pattern in Angular is sharing data between a parent component and one or more child components. You can implement this pattern by using the @ Input () and @ Output () directives. See the live example / download example for a working example containing the code snippets in this guide. Consider the following hierarchy:

How to use @input () in angular?

Use the @Input() decorator in a child component or directive to let Angular know that a property in that component can receive its value from its parent component. It helps to remember that the data flow is from the perspective of the child component. So an @Input() allows data to be input into the child component from the parent component.

How to get data from a server in angular?

Get Data from a Server A common pattern in Angular is sharing data between a parent component and one or more child components. Implement this pattern with the @ Input () and @ Output () decorators.

How do I create a nested component in angular?

A nested component is built following the same steps as any other component you might build in Angular. The @Input () Decorator can be used on a nested component property any time it needs input data from it’s parent or containing component. Any type of property can be decorated with the @Input () Decorator.


1 Answers

Angular's jqLite supports parent() method, so you could get all the parents in a loop like this:

var p = element.parent();
var allParents = [];
while (p.length > 0) {
    allParents.push(p[0]);
    p = p.parent();
}
like image 82
Bolesław Chrobry Avatar answered Sep 22 '22 07:09

Bolesław Chrobry