javascript .parents() 在 Angular 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30442576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:10:58  来源:igfitidea点击:

.parents() in Angular?

javascriptjqueryangularjs

提问by alexandernst

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

有没有一种方法可以.parents()在 Angular 中模拟 jQuery 的方法,而不必实际包含 jQuery?

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

最终目标是获取 DOM 元素的所有父元素。

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.

我正在创建一个指令(一个类似下拉菜单的小部件)。<body>如果在小部件区域之外进行了点击,下拉菜单应该监听整个点击并关闭自身(如果它是打开的)。

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

...然后我会像这样使用:<body mouse-trap .... >

$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.

这就是我需要检查被单击对象的任何父级是否是我的小部件的顶级 div 的地方,如果不是,请关闭小部件。

采纳答案by Ruairi O'Brien

EDIT:Although this answer was accepted, it's not correct. See comment and better answers below.

编辑:虽然这个答案被接受了,但它是不正确的。请参阅下面的评论和更好的答案。

It does look like jQLite supports this already so if you're using angular you should be able to do this without pulling in JQuery itself.

看起来 jQLite 已经支持这一点,所以如果您使用的是 angular,您应该能够在不引入 JQuery 本身的情况下做到这一点。

From the docs here:

这里的文档:

Supported instance methods: (links to jQuery Docs) A subset of the operations which jQuery supports are currently implemented. All of them are implemented using the chained operation syntax of jQuery. e.g:

支持的实例方法:(链接到 jQuery 文档)当前实现了 jQuery 支持的操作的子集。所有这些都是使用 jQuery 的链式操作语法实现的。例如:

$("div.foo").each(function() {
  $(this).removeClass("foo").addClass("bar");

});

});

$("div.bar, div.baz").css({ "border": "1px solid red"    }).children().addClass("child");



.parent([selector)]
.parents([selector)] 

回答by Boles?aw Chrobry

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

Angular 的 jqLit​​e 支持parent()方法,因此您可以像这样在循环中获取所有父项:

var p = element.parent();
var allParents = [];
while (p.length > 0) {
    allParents.push(p[0]);
    p = p.parent();
}

回答by Cooper Buckingham

I'm not certain you'd want to be using DOM parent references when trying to interface with Angular controllers. But not knowing what your goal is, the standard methods .parentNode, is what you're looking for. Then you'd have to loop until you hit body, or html, or null. So if you want native javascript:

我不确定在尝试与 Angular 控制器交互时您是否想要使用 DOM 父引用。但是不知道您的目标是什么,标准方法 .parentNode 就是您要寻找的。然后你必须循环直到你点击 body、html 或 null。所以如果你想要原生 javascript:

var currentParent = nodeToFindParentsOf.parentNode();
var parents = [];
while(currentParent){
  parents.push(currentParent);
  currentParent = currentParent.parentNode();
}

I'm also paranoid of while loops. So would tend to wrap that whole thing in a function and put a safety valve on it to let me know what's going on, in case of crazyness in my code or in the DOM, so I'd get a clean error, instead of locking up the browser.

我也对 while 循环感到偏执。所以倾向于将整个事情包装在一个函数中,并在其上放置一个安全阀,让我知道发生了什么,以防我的代码或 DOM 出现异常,所以我会得到一个干净的错误,而不是锁定上浏览器。

function getAllParentsOfNode (nodeToFindParentsOf) {
    var currentParent = nodeToFindParentsOf.parentNode();
    var parents = [];
    var safetyCount = 1000;
    while(currentParent){
      parents.push(currentParent);
      currentParent = currentParent.parentNode();
      if (--safetyCount  === 0) {
        throw new Error("Something went wrong. Found 1000+ parents!")
      }
    }

    return parents;
}

回答by suvartheec

Angularjs includes jqLite which contains some of the jQuery functions. details here: https://docs.angularjs.org/api/ng/function/angular.element

Angularjs 包括 jqLit​​e,其中包含一些 jQuery 函数。详情请见:https: //docs.angularjs.org/api/ng/function/angular.element

As noted in the site, it includes

如网站所述,它包括

parent() - Does not support selectors

The function provided is similar to the jQuery parent() function but will not take selectors, so you wont be able to filter using selector. From the jQuery documentation:

提供的函数类似于 jQuery parent() 函数,但不会采用选择器,因此您将无法使用选择器进行过滤。从 jQuery 文档:

This method is similar to .parents(), except .parent() only travels a single level up the DOM tree

So short answer: no it doesnt. But it does provide a small subset of it.

这么简短的回答:不,它没有。但它确实提供了它的一小部分。