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.
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:
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.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With