如何区分 2 个指令

How to distinguish between 2 directives

本文关键字:指令 何区      更新时间:2023-09-26

我正在研究 Angular i,我发现 Angular js 的指令非常令人印象深刻的功能。

在这里,我有一个问题——

假设我有 2 个指令在做类似的工作。 例如,我有 2 个指令在现有部分中添加 1 个小节,另一个指令也对其他部分做同样的事情。现在对于这 2 个指令,我需要维护 2 个指令,这些指令将适用于 2 个不同的按钮单击。

我需要知道我是否可以有 1 个指令,该指令将在按钮单击的基础上工作,并在单击按钮的部分中添加小节。

有关参考,请参阅下面的代码。

添加两个不同的按钮

mainApp.directive("addeducation", function(){
    return {
    restrict: "E",
    template: "<a href='' addedu>Click to add more sections</a>"
    }
 });
  mainApp.directive("addexperience", function(){
     return {
       restrict: "E",
        template: "<a href='' addexp>Click to add more sections</a>"
    }
  });
两个

指令在两个不同的按钮按下上工作--

  mainApp.directive("addedu", function($compile){
      return function(scope, element, attrs){
         element.bind("click", function(){
         angular.element(document.getElementById('moreeducation')).append($compile("<edu-Info></edu-Info>")(scope));
    });
};

});

 mainApp.directive("addexp", function($compile){
     return function(scope, element, attrs){
        element.bind("click", function(){
         angular.element(document.getElementById('moreexperience')).append($compile("      <experience></experience>")(scope));
       });
       };
    });

我想要这样的东西:

 mainApp.directive("addedu", function($compile){
    return function(scope, element, attrs){
    if(button1 clicked){
    then add section in experience section
    }
    else{
       add section in education section.
     }
  } 

如果有人已经遇到类似的问题,他/她可以提供帮助。我需要实现这一点,因为我不想要重复的代码。

您可以使用指令属性来区分两个指令。见下文

在您的模板中

<body ng-app="myApp">  
    <div>Education:  <add add-type = "edu"></add></div>
    <div>Experience: <add add-type = "exp"></add></div>
</body>

并在您的 JS 中

myApp.directive("add", function($compile){
return {
    restrict: "E",
    template: "<a href=''>Click to add more sections</a>",
    link: function(scope, element, attrs)
    {
        element.bind('click', function()
        {
            if(attrs.addType === 'edu')
                element.prepend($compile("<edu-Info>Add edu</edu-Info>")(scope));
            else if(attrs.addType === 'exp')
                element.prepend($compile("<experience>Add exp</experience>")(scope));
        })
    }
}

});

听起来确实是一个非常糟糕的主意,因为您要做的是将指令与其上下文耦合(知道"按钮 1"和"按钮 2"的指令)这显然不是一个很好的方法。在您描述的情况下,您可以做的是使用该指令向按钮添加对变量的引用。所以例如

"<a href='' addedu="correspondingSection">Click to add more sections</a>

然后将值添加到给定的"部分"变量(对应部分)。这样,您的指令保持通用且不区分上下文