Hi' I'm using Icheck with angularjs and I have a problem with the first switch from true to false, the $watch
on ngModel
isn't called and so it keeps value true in my angular variable. Where is the error?
This is the code
app.directive('icheck2', function ($timeout, $parse) {
return {
require: 'ngModel',
link: function ($scope, element, $attrs, ngModel) {
return $timeout(function () {
$scope.$watch($attrs['ngModel'], function (newValue) {
$(element).iCheck('update');
});
//Initialize first checkbox
if ($(element)[0].value == "true")
$(element).iCheck('check');
else
$(element).iCheck('update');//even uncheck doesn't work
return $(element).iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue'
}).on('ifChanged', function (event) {
if ($(element).attr('type') === 'checkbox' && $attrs['ngModel']) {
$scope.$apply(function () {
return ngModel.$setViewValue(event.target.checked);
})
}
});
});
}
};
});
On HTML I have:
<div data-ng-repeat="accessory in reservation.accessories"
style="margin-Top: 10px;"
data-ng-if="accessory.idType == accessoryType.CHECKBOX_TYPE">
<input icheck2 type="checkbox" name="iCheck2" data-ng-model="accessory.value"
value="{{accessory.value}}" id="checkbox{{accessory.id}}">
<span style="margin-left: 5px;">{{accessory.name}}</span>
</div>
UPDATE: I have the same problem with bootstrap switch:
app.directive('bootstrapSwitch',
[
function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
element.bootstrapSwitch({size: "small", onColor:"success", offColor:"danger"});
// ngModel.$setViewValue(false); //set start status to false
element.on('switchChange.bootstrapSwitch', function(event, state) {
if (ngModel) {
scope.$apply(function() {
ngModel.$setViewValue(state);
});
}
});
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
if (newValue) {
element.bootstrapSwitch('state', true, true);
} else {
element.bootstrapSwitch('state', false, true);
}
});
}
};
}
]
);