AngularJS的内置指令总归是有限的,特别是我们需要操纵dom时,就需要自己编写directive。
有这样一个场景,管理系统中切换状态,见图1.
图1 切换状态时的确认框效果
那么就可以定义指令“ng-confirm-click”,js:
'use strict';
//directive名字必须使用小驼峰命名法,如 ctripConfirmClick与标签中的ctrip-confirm-click属性对应。
angular.module('cepWebApp').directive('ctripConfirmClick', function() {
return {
//A:指令为标签的属性
restrict : 'A',
//link:作用在ng的链接阶段
//scope:我们经常需要在指令中访问scope对象,以便观察数据模型的值
//element:指向jquery包装后的DOM元素
//attrs:元素的属性集合
link : function(scope, element, attrs) {
//为元素绑定click()事件,jQuery用法
element.bind('click', function() {
var message = '确认启用规则?';
if (attrs.ngShow.indexOf('==') > 0)
message = '确认停用规则?';
if (confirm(message)) {
scope.$apply(attrs.ctripConfirmClickFn);
}
});
}
};
} );
html:
<td>
<a ctrip-confirm-click ng-show="item.status == 'on'" class="btn btn-success" ctrip-confirm-click-fn="stopOrStartRule(item)" >
停用
</a>
<a ctrip-confirm-click ng-show="item.status != 'on'" class="btn btn-default" ctrip-confirm-click-fn="stopOrStartRule(item)" >
启用
</a>
</td>