在angularjs中实现单个三态复选框的最佳方法是什么?

use*_*412 10 javascript checkbox tri-state-logic angularjs

有一个简单的方法来放置一个网页上的一个三态复选框并将其绑定到一个布尔模型,以便后者可以采取true,falsenull值?

到目前为止我找到的最接近的解决方案是http://jsfiddle.net/HB7LU/454/但是在设置初始视图状态时它有一个缺陷(因为在第一次渲染期间无法获得模型值).任何其他建议处理多个子复选框,并通过观看它们来解决问题.

Tru*_*inh 8

http://jsfiddle.net/xJhEG/我在一个商业项目中做到了.三位是真的,假的,无效的(不是"未知的")

.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);
        });
      }
    };
  }])
Run Code Online (Sandbox Code Playgroud)


Mau*_*ala 6

在这里,我的小提琴,从TruongSinh开始并改变

http://jsfiddle.net/xJhEG/25/

var truthy = true;
var falsy = false;
var nully = null;
Run Code Online (Sandbox Code Playgroud)


The*_*ear 5

您已经利用了 的不确定状态<input type="checkbox">

MDN 网络文档 存在一种不确定状态的复选框,其中未选中或未选中,但未确定。这是通过 JavaScript 使用 HTMLInputElement 对象的不确定属性设置的(不能使用 HTML 属性设置)。

普伦克: TRISTATE DIRECTIVE

HTML

<label>
    <input type="checkbox" ng-model="state" indeterminate /> {{state}}
</label>
Run Code Online (Sandbox Code Playgroud)

指示

app.directive('indeterminate', function() {
  return {
    restrict: 'A',
    scope: {
      model: '=ngModel'
    },
    link: function(scope, el, attrs, ctrl) {
      var states = [true, false, undefined];
      var index = states.indexOf(scope.model);
      setIndeterminate();

      el.bind('click', function() {
        scope.model = states[++index % 3];
        setIndeterminate();
      });

      function setIndeterminate() {
        scope.$applyAsync(function() {
          el[0].indeterminate = (scope.model === undefined);
        });
      }
    }
  };
});
Run Code Online (Sandbox Code Playgroud)