How to understand the `terminal` of directive?

后端 未结 1 1467
感动是毒
感动是毒 2020-11-28 03:07

In this page: http://docs.angularjs.org/guide/directive

Directive Definition Object

terminal

If set to true then the curre

相关标签:
1条回答
  • 2020-11-28 03:29

    Priority

    The priority is only relevant when you have multiple directives on one element. The priority determines in what order those directives will be applied/started. In most cases you wouldn't need a priority, but sometimes when you use the compile function, you want to make sure that your compile function runs first.

    Terminal

    The terminal property is also only relevant for directives that are on the same HTML element. That is, if you have <div my-directive1></div> <div my-directive2></div>, priority and terminal in your directives my-directive1 and my-directive2 won't affect each other. They will only affect each other if you have <div my-directive1 my-directive2></div>.

    The terminal property tells Angular to skip all directives on that element that comes after it (lower priority). So this code might clear it up:

    myModule.directive('myDirective1', function() {
        return {
            priority: 1,
            terminal: false,
            link: function() {
                console.log("I'm myDirective1");
            }
        }
    });
    
    myModule.directive('myDirective2', function() {
        return {
            priority: 10,
            terminal: true,
            link: function() {
                console.log("I'm myDirective2");
            }
        }
    });
    
    myModule.directive('myDirective3', function() {
        return {
            priority: 100,
            terminal: false,
            link: function() {
                console.log("I'm myDirective3");
            }
        }
    });
    

    For this, you'd only see "I'm myDirective2" and "I'm myDirective3" in the console.

    <div my-directive1 my-directive2 my-directive3></div>
    

    But for this, you'd see "I'm myDirective1" as well, since they are on different elements.

    <div my-directive1></div>
    <div my-directive2></div>
    <div my-directive3></div>
    

    Original post

    In your example the directives with priority 100 and 1000 are the only ones that will get applied, since a directive with higher priority are applied first, so the one with priority 1000 will be applied first.

    If you have two directives with priority 100 in this case, both of them will be applied because the order of directives with the same priority is undefined.

    Note that this only applies to directives that are on the same element.

    0 讨论(0)
提交回复
热议问题