gpt4 book ai didi

javascript - 如何捕获指令中的复选框事件?

转载 作者:行者123 更新时间:2023-11-28 06:58:16 25 4
gpt4 key购买 nike

我是 Angular 的新手,想要在指令中调用和捕获 Checkbox 事件 (checked/unchecked)。因此,这意味着当有人选中该复选框时,它应该调用 links|controller 中的某些代码/函数;理想情况下,在指令的 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;
});

理想情况下,我希望在每个选中和未选中事件中调用此指令,并捕获事件值,但主要关注的是在选中复选框时调用此指令。

有人可以告诉我如何做到这一点吗?

最佳答案

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

只需将其设置为您的复选框即可:

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

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

如果你还坚持自己写,就看ng-change source code 。只需根据您的需要进行调整即可。

关于javascript - 如何捕获指令中的复选框事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32382620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com