最近在做項目時,遇到了需要用到多選按鈕選中觸發事件的功能,因此我查找了一下AngularJS的提供的指令,但是沒有發現相應的指令。而一個看起來很像的指令就是ng-checked,但是這個指令是用來代替標簽里面checked屬性的,所以也用不了。因此我就自己動手試著寫一個這樣的指令,相應的代碼如下:
<form name="test_form" ng-controller="TestCtrl"><input type="checkbox" name="a" ng-model="a" id="check" ng-checking="say()"/><label for="check">{{ a }}</label></form>var app = angular.module('Demo',[]);app.directive('ngChecking',function(){var fun1 = function(element,attrs){return function(scope,iElement,iAttrs){scope.$watch('a',function(){if(iElement[0].checked){if(iAttrs['ngChecking']){ var fun = iAttrs['ngChecking'].match(//w+()/g);scope[fun[0]]();}}})}}return {compile:fun1,restrict:'AE'}})app.controller('TestCtrl',function($scope){$scope.say = function(){alert(123)}});angular.bootstrap(document,['Demo']);
總結
以上所述是小編給大家介紹的使用AngularJS編寫多選按鈕選中時觸發指定方法的指令代碼詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答