I created one directive for checkbox which makes an image layer, but problem is that it's not firing ng change event if even input box checked value is changed
Directive
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 BELOW
<input type="checkbox" class="i-checks" data-icheck ng-change="alert('changed!')" ng-model="chekal" id="chkSelectAll">
Any idea how I can trigger ng change event on even click event will be fine.
Documentation of ngChange:
Evaluate the given expression when the user changes the input
If you want to watch the model, use $scope.watch
$scope.$watch('chekal', function(newvalue,oldvalue) {
if (newvalue !== oldvalue){
//write code here
}});
What i did was passing funciton value in attribute
<input type="checkbox" class="i-checks" data-icheck data-function="selectAll" ng-model="chekal" id="chkSelectAll">
directive
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);
});
}
so I called the function with that eval thing. This answer is just for reference so it can help others as well.
I don't wanted to add adhoc of watches so did it without increasing watches and solved question with more performance way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With