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

时间:2022-11-03 14:55:27

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? Or/Also how might you make a directive that does different things depending upon ID, Class or other properties?

您将如何创建仅对具有指令名称和ID,类或其他属性的某些元素执行操作的指令?或者/你如何根据ID,Class或其他属性制定一个不同的指令呢?

I don't mean the type of thing where you create a directive as a class, and just use 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. 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?

我不是指作为类创建指令的类型,而只是使用ngClass。作为一个例子......想象一下,用户正在定义HTML的一部分并且我无法触摸它,但我知道会有一个带有ul和li的导航标签。如何制作可以应用于具有id =“navi”的nav标签的指令,而不会影响页面上的其他导航标签(如果有的话)?


To be clear, I come from a jQuery background, so I'm trying to unlearn a lot of bad habits lol. 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?

要清楚,我来自jQuery背景,所以我试图忘掉很多坏习惯。我已经习惯了通过$选择元素或元素集合的概念,并应用某种操作或者你有什么。在我无法直接触摸部分HTML的情况下,如何实现这种类型的功能选择性过滤?

1 个解决方案

#1


2  

You have access to the element at hand as well at the attributes of that element within the link function. Example concerning you <nav id="navi"> case:

您可以访问手头的元素以及链接函数中该元素的属性。关于你的示例

<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. attrs is an object with all of the elements attributes as well.

如您所见,您可以在链接函数中检查元素的特定属性。 attrs是一个具有所有元素属性的对象。

#1


2  

You have access to the element at hand as well at the attributes of that element within the link function. Example concerning you <nav id="navi"> case:

您可以访问手头的元素以及链接函数中该元素的属性。关于你的示例

<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. attrs is an object with all of the elements attributes as well.

如您所见,您可以在链接函数中检查元素的特定属性。 attrs是一个具有所有元素属性的对象。