角度指令。我可以取消优先级较低的指令吗?

时间:2014-09-17 18:30:05

标签: angularjs angularjs-directive

假设我有一个带有几个指令的元素。 例如:

<div myFirstDirective='someFn'  mySecondDirective></div>

(myFirstDirective的优先级高于mySecondDirective)

因此,在这种情况下,如果myFirstDirective从函数返回false值,我甚至不希望mySecondDirective“运行”。 这甚至可能吗?

如果是这样,我将如何“取消”第二条指令?

有任何洞察力的谢谢

2 个答案:

答案 0 :(得分:2)

你需要他们通过呼叫另一个人的控制器来互相交谈。

app.directive('myFirstDirective', function() {
  return {
     restrict: 'A', 
     priority: 20,
     controller: function ($scope) {
         var result = false;
         if ($scope.myFirstDirective) {
             result = $scope.myFirstDirective();
         }
         this.shouldRun = function() {
             return result;
         }
     },
     scope: { myFirstDirective: '&' }
  }
});

app.directive('mySecondDirective', function() {
  return {
     restrict: 'A', 
     priority: 10,
     require: '?myFirstDirective',
     link: function(scope, element, attr, otherController) {
         if(otherController && otherController.shouldRun()) {
             // execute this directive only if 
             // function from first directive returns true.
         }

     }
  }
});

答案 1 :(得分:0)

您可以在mySecondDirective链接函数中评估myFirstDirective属性的结果。如果没有应用正确的值,则立即退出链接功能。

link: function(scope, element, attributes) {
    //link of mySecondDirective
    var firstValue = scope.$eval(attributes.myFirstDirective);
    if (!firstValue) return;

    // else do some cool stuff
}