[英]ng change event not firing on checkbox if it's set by javascript
我为创建图像层的复选框创建了一个指令,但是问题是,即使输入框的检查值被更改,它也不会触发ng change事件
指示
function icheck($timeout,$parse) {
return {
restrict: 'A',
link: function ($scope, element, $attrs, $watch) {
var value = $attrs['value'],
ngModelGetter = $parse($attrs['ngModel']);
return $timeout(function () {
$scope.$watch($attrs.ngModel, function (newValue) {
$(element).iCheck('update');
});
$(element).iCheck({
checkboxClass: 'icheckbox_square-green',
radioClass: 'iradio_square-green'
}).on('ifChanged', function (event) {
var elemType = $(element).attr('type');
if (elemType === 'checkbox' && $attrs.ngModel) {
$scope.$apply(function () {
console.log(event.target.checked)
return ngModelGetter.assign($scope, event.target.checked);
});
}
else if (elemType === 'radio' && $attrs.ngModel) {
return $scope.$apply(function () {
return ngModelGetter.assign($scope, value);
});
}
});
});
}
};
}
下方的HTML
<input type="checkbox" class="i-checks" data-icheck ng-change="alert('changed!')" ng-model="chekal" id="chkSelectAll">
我知道如何在单击事件上触发ng change事件的任何想法都可以。
ngChange的文档:
当用户更改输入时评估给定表达式
如果要观看模型,请使用$scope.watch
$scope.$watch('chekal', function(newvalue,oldvalue) {
if (newvalue !== oldvalue){
//write code here
}});
我所做的是在属性中传递函数值
<input type="checkbox" class="i-checks" data-icheck data-function="selectAll" ng-model="chekal" id="chkSelectAll">
指示
if (elemType === 'checkbox' && $attrs.ngModel) {
$scope.$apply(function () {
console.log(event.target.checked)
var f = $(event.target).data('function');
console.log(f);
if (f !== "undefined" || f !== "") {
eval('$scope.' + f + '(event)');
}
return ngModelGetter.assign($scope, event.target.checked);
});
}
所以我用那个评估对象来调用函数。 该答案仅供参考,因此也可以为他人提供帮助。
我不想增加手表的特殊性,所以不增加手表,而是以更多的性能方式解决了问题。
将您的icheck
函数更改为directive
,如下所示:
yourapp.directive('icheck', function($timeout,$parse) {
return {
restrict: 'A',
link: function ($scope, element, $attrs, $watch) {
var value = $attrs['value'],
ngModelGetter = $parse($attrs['ngModel']);
return $timeout(function () {
$scope.$watch($attrs.ngModel, function (newValue) {
$(element).iCheck('update');
});
$(element).iCheck({
checkboxClass: 'icheckbox_square-green',
radioClass: 'iradio_square-green'
}).on('ifChanged', function (event) {
var elemType = $(element).attr('type');
if (elemType === 'checkbox' && $attrs.ngModel) {
$scope.$apply(function () {
console.log(event.target.checked)
return ngModelGetter.assign($scope, event.target.checked);
});
}
else if (elemType === 'radio' && $attrs.ngModel) {
return $scope.$apply(function () {
return ngModelGetter.assign($scope, value);
});
}
});
});
}
};
});
然后将data-i-check
作为属性添加到输入标签,而不是data-icheck
。
<input type="checkbox" class="i-checks" data-i-check ng-change="alert('changed!')" ng-model="chekal" id="chkSelectAll">
$scope.$watch('chekal', function(newvalue,oldvalue) {
if (newvalue && newvalue !== oldvalue){
// here you go
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.