通过取消选中带有指令的复选框来更新模型

时间:2013-08-23 22:08:44

标签: angularjs angularjs-directive

所以我想要做的是与复选框的依赖。因此,取消选中它所依赖的复选框后,将禁用+取消选中相关复选框。出于某种原因,取消选中指令内的复选框可以完成工作,就像禁用和取消选中它一样,但绑定到它的模型不会更新。

HTML:

<div>
  <input type="checkbox" data-ng-model="test.dependency"/>
  <span>unchecking this one will disable the next</span>
</div>

<div>
  <input dependent="test.dependency" type="checkbox" data-ng-model="test.optional" />
  <span>this checkboxs directive will uncheck it when the first one is unchecked, but the model doesn't get updated, not it's {{test.optional}}</span>
</div>

控制器(默认选项):

$scope.test = {
  dependency: true,
  optional: false
}

指令:

restrict: 'A',
link: function(scope,elem,attrs){
  scope.$watch(attrs.dependent,function(val){
    if (!val){
      elem[0].checked = false;
      elem[0].disabled = true
    } else {
      elem[0].disabled = false
    }
  })
}

编辑:对,here's插件。

1 个答案:

答案 0 :(得分:6)

由于您正在将指令应用于已使用ng-model指令的元素,因此您需要告诉ng-model更新模型和视图:

app.directive('dependent', function(){
  return {
    restrict: 'A',
    require: 'ngModel', // Requires the NgModelController to be injected
    link: function(scope,elem,attrs, ngModelCtrl){
      scope.$watch(attrs.dependent, function(val){
        if (!val) {
          elem[0].disabled = true;
          ngModelCtrl.$setViewValue(); // Updates the model
          ngModelCtrl.$render();       // Updates the view 
        } else {
          elem[0].disabled = false
        }
      });
    }
  }
});

Plunker here

查看NgModelController documentation了解详情。