2013-08-23 15 views
3

所以我試圖做的是使用複選框的依賴關係。所以這個依賴複選框將被取消選中,一旦它所依賴的複選框被取消選中。出於某種原因,取消選中指令中的複選框可以執行該作業,例如禁用和取消選中該選項,但綁定到該模型的模型不會更新。通過取消選中一個指令複選框來更新模型

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的普拉克。

回答

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瞭解更多詳情。

相關問題