<table class="text">
<tr class="li1"><td class="ln"><pre class="de1">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59 插件用angularjs的方式封装成组件的例子 icheck是一个jquery插件,用于跨浏览器美化CheckBox和Radio按纽。关于它的介绍,在http://www.bootcss.com/p/icheck/ 一般来说,它的使用方法是在dom载入后加一段jquery代码: $('input').iCheck({ labelHover : false, cursor : true, checkBoxClass : 'icheckBox_square-blue', radioClass : 'iradio_square-blue', increaseArea : '20%' }); 但是既然要放在我们的项目里,就不能到处塞这种直接操作dom的jquery代码,既不美观,也不易维护。按照之前所说的原则,最好将其封装成angular指令的模式,放在公共模块里来调用。这里我将我新建的指令命名为ng-icheck。如此,我们只要写在某个checkBox或者radio的html标签里加上一句ng-ickeck即可。具体实现如下: /* * angular directive ng-icheck * * @description icheck is a plugin of jquery for beautifying checkBox & radio,now I complied it with angular directive * @require jquery,icheck * @example * */ $compileProvider.directive('ngIcheck',function($compile) { return { restrict : 'A', require : '?ngModel', link : function($scope,$element,$attrs,$ngModel) { if (!$ngModel) { return; } //using iCheck $($element).iCheck({ labelHover : false, cursor : true, checkBoxClass : 'icheckBox_square-blue', radioClass : 'iradio_square-blue', increaseArea : '20%' }).on('ifClicked',function(event) { if ($attrs.type == "checkBox") { //checkBox,$ViewValue = true/false/undefined $scope.$apply(function() { $ngModel.$setViewValue(!($ngModel.$modelValue == undefined ? false : $ngModel.$modelValue)); }); } else { // radio,$ViewValue = $attrs.value $scope.$apply(function() { $ngModel.$setViewValue($attrs.value); }); } }); }, }; }); 在以上代码中值得注意的是:使用了icheck插件后,会生成一个美化过的div覆盖在原来的checkBox或者radio之上,而原来的checkBox或者radio会被影藏。故而,当我们点击它们时,不会直接触发事件,使得绑定到checkBox或者radio上的model值改变。所以我们这里需要重新绑定事件,使用 $ngModel.$setViewValue() 方法来给model赋值。具体逻辑,则相根据checkBox和radio而不同。详见以上代码。 由于以上代码写在我的项目中的通用模块common_angular_component.js里,故而在调用了该通用模块的页面里,直接使用ng-icheck指令即可实现ickeck的美化效果,同时避免了大量重复的jquery代码的出现。