使用AngularJS编写多选按钮选中时触发指定方法的指令

  最近在做项目时,遇到了需要用到多选按钮选中触发事件的功能,因此我查找了一下AngularJS的提供的指令,但是没有发现相应的指令。而一个看起来很像的指令就是ng-checked,但是这个指令是用来代替标签里面checked属性的,所以也用不了。因此我就自己动手试着写一个这样的指令,相应的代码如下:

1 <form name="test_form" ng-controller="TestCtrl">
2   <input type="checkbox" name="a" ng-model="a" id="check" ng-checking="say()"/>
3   <label for="check">{{ a }}</label>
4 </form>
 1 var app = angular.module('Demo',[]);
 2 app.directive('ngChecking',function(){
 3     var fun1 = function(element,attrs){
 4     return function(scope,iElement,iAttrs){
 5         scope.$watch('a',function(){
 6           if(iElement[0].checked){
 7             if(iAttrs['ngChecking']){             
 8               var fun = iAttrs['ngChecking'].match(/\w+()/g);
 9             scope[fun[0]]();
10           }
11         }
12       })
13     }
14     
15   }
16     return {
17          compile:fun1,
18       restrict:'AE'
19   }
20 })
21 app.controller('TestCtrl',function($scope){
22     $scope.say = function(){
23       alert(123)
24   }
25 });
26 angular.bootstrap(document,['Demo']);

  亲试可用,AngularJS的功能真的是很强大。

posted @ 2016-01-20 15:47  牧云人生  阅读(379)  评论(0编辑  收藏  举报