jsfiddle here 。 我一直在尝试指令优先级和终端属性。我创建了三个指令,优先级分别为 3、2 和 1。主指令(最高优先级,优先级:3)有一个模板,该模板创建一个按钮,单击该按钮会调用该指令 Controller 上的一个方法。一切正常,直到我将terminal: true放在优先级2指令上。由于某种原因导致按钮停止工作;主指令(优先级 3)渲染良好,但单击按钮不会执行任何操作。再说一次,这是 jsfiddle ,这是指令的代码:
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>
最佳答案
调试 AngularJS 代码(特别是 applyDirectivesToNode here ),当您设置 terminal:true
时看起来就像这样在您的finnish
上指令最终停止 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('नमस्ते');
}
};
});
关于AngularJS 终端指令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16352722/