我是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
事件中调用此指令,并且还捕获事件值,但主要关注的是在选中复选框时调用此指令。
有人可以告诉我怎么办?
答案 0 :(得分:0)
您尝试执行的指令已存在,名为ng-change
只需将其设置为您的复选框:
<input type="checkbox" ng-change="yourController.reactOnChangedValue($event)">
检查给定的网址,他们有一个足以满足您目的的示例。
如果您仍然坚持自己编写,请查看ng-change source code。只需根据您的需求进行调整。