如何在指令中捕获复选框事件

How to capture checkbox event in directive?

本文关键字:复选框 事件 指令      更新时间:2023-09-26

我是Angular的新手,想在指令中调用和捕获Checkbox事件(checked/unchecked)。所以这意味着当有人选中复选框时,它应该在links|controller中调用一些代码/函数;理想情况下,在指令的控制器中避免使用$watch。下面是我目前得到的结果:

<!-- this reside in a different view under some controller called 'myCtrl' -->
<input my-directive type="checkbox">  
angular.module('myApp').directive('myDirective', function () {
   var directive = {};
   directive.restrict = 'A';
   directive.controller = ['$scope', '$rootScope', function ($scope, $rootScope) {
        // maybe capture checkbox event here
   }];
   directive.compile = function () {
       var linkingFunction = function (scope, element, attributes, ngModel) {
       // or capture event here and do some logic 
       // logic might look like below in pseudo code
       if (input element is checked ) {
           do something 
           also store the capture value in a variable i.e. `checked`
       } 
       if (input is uncheched) {
           then do this other thing 
           also store the capture value in a variable i.e. `unchecked`
       } 
       };
       return linkingFunction;
   };
   return directive;
});

理想情况下,我想用每个checked and unchecked事件调用此指令,并且还捕获事件值,但主要关注的是当复选框被选中时调用此指令。

谁能告诉我怎么做?

您尝试执行的指令已经存在,并且名为ng-change

把它设置为你的复选框:

<input type="checkbox" ng-change="yourController.reactOnChangedValue($event)">

检查给定的URL,他们有一个例子,应该足以满足您的目的。

如果你仍然坚持自己写,只要看看ng-change源代码。