嗨'我正在使用Icheck和angularjs,我遇到第一次从true切换到false的问题,$watch
上的ngModel
没有被调用,所以它保持不变在我的角度变量中值为true。错误在哪里?
这是代码
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);
})
}
});
});
}
};
});
在HTML上我有:
<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>
更新:我在bootstrap开关时遇到同样的问题:
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);
}
});
}
};
}
]
);