一个干净的指令方法。
更新:旧答案(2014)
它基本上拦截ng-click
事件,显示ng-confirm-click="message"
指令中包含的消息并要求用户确认。如果单击确认,则正常ng-click
执行,否则脚本终止并且ng-click
不运行。
<!-- index.html -->
<button ng-click="publish()" ng-confirm-click="You are about to overwrite your PUBLISHED content!! Are you SURE you want to publish?">
Publish
</button>
// /app/directives/ng-confirm-click.js
Directives.directive('ngConfirmClick', [
function(){
return {
priority: -1,
restrict: 'A',
link: function(scope, element, attrs){
element.bind('click', function(e){
var message = attrs.ngConfirmClick;
// confirm() requires jQuery
if(message && !confirm(message)){
e.stopImmediatePropagation();
e.preventDefault();
}
});
}
}
}
]);
Zach Snow 的代码信用:http: //zachsnow.com/# !/blog/2013/confirming-ng-click/
更新:新答案(2016)
1) 将前缀从 'ng' 更改为 'mw',因为前者 ('ng') 是为原生 Angular 指令保留的。
2) 修改指令以传递函数和消息,而不是拦截 ng-click 事件。
3) 添加了默认的“你确定吗?” 未向 mw-confirm-click-message="" 提供自定义消息的情况下的消息。
<!-- index.html -->
<button mw-confirm-click="publish()" mw-confirm-click-message="You are about to overwrite your PUBLISHED content!! Are you SURE you want to publish?">
Publish
</button>
// /app/directives/mw-confirm-click.js
"use strict";
var module = angular.module( "myApp" );
module.directive( "mwConfirmClick", [
function( ) {
return {
priority: -1,
restrict: 'A',
scope: { confirmFunction: "&mwConfirmClick" },
link: function( scope, element, attrs ){
element.bind( 'click', function( e ){
// message defaults to "Are you sure?"
var message = attrs.mwConfirmClickMessage ? attrs.mwConfirmClickMessage : "Are you sure?";
// confirm() requires jQuery
if( confirm( message ) ) {
scope.confirmFunction();
}
});
}
}
}
]);