问题描述
是否有一种简单的方法可以在网页上放置单个三态复选框并将其绑定到布尔模型,以便后者可以采用 true
、false
还是 null
值?
Is there a simple way to place a single tri-state checkbox on a web-page and bind it to a boolean model so the latter can take true
, false
or null
values?
到目前为止我找到的最接近的解决方案是 http://jsfiddle.net/HB7LU/454/ 但它有一个设置初始视图状态时的缺陷(因为在第一次渲染期间无法获取模型值).任何其他建议处理多个子复选框并通过观察它们来解决问题.
The closest solution I found so far is http://jsfiddle.net/HB7LU/454/ but it has a flaw when setting up an initial view state (as there is no way to get a model value during first rendering). Any other suggestions deal with multiple child checkboxes and solves the problem by watching on them.
推荐答案
http://jsfiddle.net/xJhEG/ 我是在一个商业项目中做到的.三态是真、假、空(不是未知")
http://jsfiddle.net/xJhEG/ I made it in a commercial project. Tristates are true, false, null (not "unknown")
.directive('indeterminate', [function() {
return {
require: '?ngModel',
link: function(scope, el, attrs, ctrl) {
var truthy = true;
var falsy = false;
var nully = null;
ctrl.$formatters = [];
ctrl.$parsers = [];
ctrl.$render = function() {
var d = ctrl.$viewValue;
el.data('checked', d);
switch(d){
case truthy:
el.prop('indeterminate', false);
el.prop('checked', true);
break;
case falsy:
el.prop('indeterminate', false);
el.prop('checked', false);
break;
default:
el.prop('indeterminate', true);
}
};
el.bind('click', function() {
var d;
switch(el.data('checked')){
case falsy:
d = truthy;
break;
case truthy:
d = nully;
break;
default:
d = falsy;
}
ctrl.$setViewValue(d);
scope.$apply(ctrl.$render);
});
}
};
}])
这篇关于在 angularjs 中实现单个三态复选框的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!