0

我正在使用 Angular 和 Bootstrap。我正在尝试为引导复选框复制 ng-model 的功能。我想要完成的是:

我希望当我单击复选框(实际上是标签)时,模型会发生变化,实际上这有效......但是当我尝试观察对象以进行更改时,行为是奇怪的,因为我需要两次点击设置为禁用或启用复选框。此外,如果在具有属性 cm-checkbox="model.prop" 的标签元素内,我放置一个 {{model.anotherprop}} 将不起作用(不呈现任何内容)。

从文档中我了解到,因为我想要双向数据绑定,所以必须像我一样定义范围。

谢谢您的帮助!

我有以下 HTML:

<label id="claim_free" class="checkbox" for="checkbox1" cm-checkbox="model.prop">
      <span class="icons"><span class="first-icon fui-checkbox-unchecked"></span><span class="second-icon fui-checkbox-checked"></span></span><input name="claim_free" type="checkbox" value="" data-toggle="checkbox">
      same lable text
</label>

以及以下JS:

directive('cmCheckbox', function() {
  return {
    restrict: 'A',
    scope: {'cmCheckbox':'='},
    link: function(scope,elm,attrs) {
      scope.$watch('cmCheckbox', function() {
          console.log("first value for "+attrs.cmCheckbox+" is: "+scope.cmCheckbox);
          if (!scope.cmCheckbox) {
            console.log("checked");
            $(elm).removeClass("checked");
            $(elm).children("input").removeAttr("checked");
          } else { // false and undefined
            console.log("unchecked");
            $(elm).addClass("checked");
            $(elm).children("input").attr("checked","checked");
          }
      });
      $(elm).on('click', function(e) {
        e.preventDefault();
        var currentValue = elm.hasClass("checked") ? false : true;
        scope.$apply(function() {
          scope.cmCheckbox = currentValue;
        },true);
        scope.$parent.$apply();
      });
    }
  };
}).

这是 jsFiddle:jsfiddle.net/pmcalabrese/66pCA/2

4

0 回答 0