简体   繁体   English

如果元素具有Id或Class(角),则应用Apply指令

[英]Apply directive if element has Id or Class (angular)

This is a general problem I've run into while trying to learn angular. 这是我尝试学习角度学习时遇到的一个普遍问题。

How would you create a directive that only acts on certain elements which have the directive name AND an ID, Class, or other property? 您将如何创建仅对具有指令名称和ID,类或其他属性的某些元素起作用的指令? Or/Also how might you make a directive that does different things depending upon ID, Class or other properties? 或/还有,您将如何根据ID,Class或其他属性制定一个执行不同操作的指令?

I don't mean the type of thing where you create a directive as a class, and just use ngClass . 我并不是说您将指令创建为类,而仅使用ngClass As an example... Imagine a scenario where a user is defining part of the HTML and I can't touch it, but I know that there will be a nav tag with ul's and li's inside of it. 举个例子……想像一下一个场景,用户正在定义HTML的一部分,而我却无法触摸它,但是我知道在其中将包含带有ul和li的nav标签。 How do I make a directive that can be applied to the nav tag that has id="navi" without affecting the other nav tags on the page if there are any? 如何制定可应用于具有id="navi"的nav标签的指令,而不影响页面上的其他nav标签(如果有)?


To be clear, I come from a jQuery background, so I'm trying to unlearn a lot of bad habits lol. 明确地说,我来自jQuery背景,所以我试图学习很多坏习惯,哈哈。 I'm very used to the concept of selecting an element, or a collection of elements via $ and applying some kind of manipulation or what have you. 我非常习惯于通过$选择元素或元素集合并进行某种操作或拥有什么的概念。 How can I achieve this type of selective filtering of functionality in a scenario where I'm not able to touch parts of the HTML directly? 在无法直接触摸HTML部分的情况下,如何实现这种类型的功能选择性过滤?

You have access to the element at hand as well at the attributes of that element within the link function. 您可以在link函数中访问手边的element以及该元素的属性。 Example concerning you <nav id="navi"> case: 有关您<nav id="navi">情况的示例:

<nav my-directive id="navi"></nav>

Directive time! 指令时间!

.directive("myDirective", [function() {
    return {
        restrict: "A",
        link: function(scope, elem, attrs) {
            if (elem[0].id == "navi") {
                //apply specific condition to elem here
            }
        }
    }
}]);

As you can see, you can check specific properties of the element within the link function. 如您所见,您可以在链接函数中检查element特定属性。 attrs is an object with all of the elements attributes as well. attrs是一个具有所有elements属性的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM