2013-05-03 77 views
3

jsfiddle here。 我一直在试验指令优先级和终端属性。我已经创建了三个优先级为3,2和1的指令。主指令(最高优先级,优先级:3)具有一个创建按钮并单击该按钮的模板来调用指令控制器上的方法。一切正常,直到我把终端:真正的优先级2指令。有些原因导致按钮停止工作;主指令(优先级3)呈现正常,但单击该按钮不会执行任何操作。同样,这里是jsfiddle,这里是对指令代码:AngularJS终端指令不工作

myApp = angular.module('myApp', []) 
    .directive('greeting', function() { 
     return { 
      restrict: 'E', 
      replace: true, 
      priority: 3, 
      template: "<button class='btn' ng-click='sayHello()'>Say Hello</button>", 
      controller: function($scope) { 
       var greetings = ['hello']; 
       $scope.sayHello = function() { 
        alert(greetings.join()); 
       } 
       this.addGreeting = function(greeting) { 
        greetings.push(greeting); 
       } 
      } 
     }; 
    }) 
    .directive('finnish', function() { 
     return { 
      restrict: 'A', 
      priority: 2, 
      terminal:true, 
      require: 'greeting', 
      link: function(scope, element, attrs, controller) { 
       controller.addGreeting('hei'); 
      } 
     }; 
    }) 
    .directive('hindi', function() { 
     return { 
      restrict: 'A', 
      priority: 1, 
      require: 'greeting', 
      link: function(scope, element, attrs, controller) { 
       controller.addGreeting('नमस्ते'); 
      } 
     }; 
    }); 

在页面上的HTML看起来像这样:

<body ng-app="myApp"> 
    <greeting finnish hindi /> 
</body> 

回答

4

调试AngularJS代码(尤其是applyDirectivesToNode here)看起来就像您在finnish指令上设置terminal:true一样,它会停止ng-click(本身指令设置为优先级0,低于优先级2)的处理。所以点击按钮什么也不做。

Here is a modified fiddle将您指令的优先级分别更改为0,-1和-2,以免终止ng-click

myApp = angular.module('myApp', []) 
    .directive('greeting', function() { 
     return { 
      restrict: 'E', 
      replace: true, 
      priority: 0, 
      template: "<button class='btn' ng-click='sayHello()'>Say Hello</button>", 
      controller: function($scope) { 
       var greetings = ['hello']; 
       $scope.sayHello = function() { 
        alert(greetings.join()); 
       } 
       this.addGreeting = function(greeting) { 
        greetings.push(greeting); 
       } 
      } 
     }; 
    }) 
    .directive('finnish', function() { 
     return { 
      restrict: 'A', 
      priority: -1, 
      terminal:true, 
      require: 'greeting', 
      link: function(scope, element, attrs, controller) { 
       controller.addGreeting('hei'); 
      } 
     }; 
    }) 
    .directive('hindi', function() { 
     return { 
      restrict: 'A', 
      priority: -2, 
      require: 'greeting', 
      link: function(scope, element, attrs, controller) { 
       controller.addGreeting('नमस्ते'); 
      } 
     }; 
    }); 
+0

这完全有道理!感谢您深入挖掘! – 2013-05-03 22:18:38

0

@Jim库珀,如果你使用角度-1.2.1,你会得到“你好,HIE”作为按钮的点击输出。我相信这应该是输出。否则,问候语的优先级需要根据在模板化html中使用的指令的优先级来设置。这会让人困惑,如果我们在模板化HTML内部引入具有不同优先级的自定义指令以及一些内置指令。