在给定的 HTML 元素上,您可以定义指令的链接顺序而无需硬编码 priority
在指令中允许独立指令链接?
示例:
假设对于给定的元素点击,我们想要
- 检查用户是否已通过身份验证
- 记录操作
- 加载数据
- 提交表单。
但是,步骤 1-4 都是单一职责,并且彼此不了解。一般来说,步骤 4 不依赖于步骤 1-3,因此以下都是有效按钮:
<button check-user-is-authenticated log-some-action load-new-data submit-form></button>
<button submit-form log-some-action></button>
<button check-user-is-authenticated submit-form></button>
但是,各个按钮确实知道指令应该运行的顺序:for <button submit-form log-some-action></button>
,我们要提交表单然后记录数据。
checkUserIsAuthenticated 指令的示例。其他指令类似。
MyApp.directive('checkUserIsAuthenticated', ['app', (app) ->
{
restrict: 'A',
link: ( scope, element, attrs ) ->
element.bind( "click", (event) ->
if(app.authenticated)
#continue running directives
true
else
#Go and authenticate then continue with any other directives
app.goAuthenticate()
)
}
])
大多数指令不依赖于当前 Controller /作用域,因此使用 Controller 来处理此问题会在应用程序中的许多 Controller 中添加大量代码重复。
最佳答案
只有一种方法可以解决您的问题:
编写一个处理点击事件并调用提供的服务方法的指令:
<button chained-actions="a:b:c">Action a b c</button>
模块定义:
angular.module('myApp', [])
.factory('a', function($http){
return function(){
console.log('A');
}
})
.factory('b', function($http){
return function(){
console.log('B');
}
})
.factory('c', function($http){
return function(){
console.log('C');
}
})
.directive('chainedActions', function($injector){
return function($scope, $element, $attr){
$element.on('click', function(){
$scope.$apply(function(){
var actions = $attr.chainedActions.split(':')
angular.forEach(actions, function(action){
var actionServie = $injector.get(action);
actionServie();
});
});
});
};
})
;
关于javascript - 在 AngularJS 中,您可以为每个元素使用不同的定义顺序来链接属性指令事件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21042364/