2014-01-12 21 views
1

我有一个组中有三个单选按钮的窗体。第三个单选按钮是“其他”,并有一个文本字段,用户可以在其中输入内容。通过向单选按钮的输入元素添加“required”属性,我可以创建所需的单选按钮。但是,如果且仅当选中“其他”单选按钮时,才会使文本字段成为必需。我怎样才能做到这一点?带有“其他”选项的AngularJS单选按钮组,包含文本域

<p> 
    Program: 
    <label><input type="radio" ng-model="form.Program" name="Program" value="option 1" required /> option 1</label> 
    <label><input type="radio" ng-model="form.Program" name="Program" value="option 2" required /> option 2</label> 
    <label><input type="radio" ng-model="form.Program" name="Program" value="other" required /> other</label> 
    <input type="text" ng-model="form.OtherProgram" ng-disabled="form.Program != 'other'" name="Program_Other" /> 
</p> 

,我想这样做的另一件事就是以某种方式确保在“其他条件”未选中,那么$ scope.form.OtherProgram是空白,同时使屏幕,以便在文本如果它被重新选择,则用户不必重新输入文本字段中的内容。

回答

2

您可以使用ng-required。像

<input type ="text" ng-required ="form.Program != 'other'"> 

应该工作。

关于你的其他问题,你必须使用一些控制器逻辑和form.OtherProgram的某种临时变量,例如使用$ watch。

$scope.$watch('form.Program', function(mVal){ 
    if (angular.isUndefined($scope.form)) return; 

    if(mVal === 'other'){ 
    $scope.form.OtherProgram = $scope.tmVar; 
    } else { 
    if($scope.form.OtherProgram !== null){ 
     $scope.tmVar = $scope.form.OtherProgram; 
     $scope.form.OtherProgram = null; 
    } 
} 
}); 

Plunker:http://plnkr.co/edit/npvUXpRhB5MYJOstwd88?p=preview

+0

NG-需要伟大的工作;谢谢!如果'form.Program!='other''有什么想法让我的模型显示一个空字符串?我开始明白我可能需要以某种方式绑定到隐藏字段(因为angularJS正在执行双向绑定)。 –

+0

你也可以尝试使用ng-change来表现更具表现力。由于角度已经提到了双向绑定,所以隐藏的输入域对你来说帮助不大。 –

+0

您的$ watch工作,虽然我注意到在页面加载的控制台窗口中的JavaScript引用错误,所以我添加了以下guard子句的函数:'if(angular.isUndefined($ scope.form))return;'。但是,如果我选择“其他”,请键入内容,然后选择选项1,然后选择选项2,然后再次选择“其他”,文本框为空。 –

0

这里是我结束了。这是对hugo答案的轻微变化。主要区别在于“其他”文本在屏幕上保持可见。我只是认为我会将这作为一种替代方法来记录。

<p> 
    Program: 
    <label><input type="radio" ng-model="form.Program" name="Program" value="option 1" required /> option 1</label> 
    <label><input type="radio" ng-model="form.Program" name="Program" value="option 2" required /> option 2</label> 
    <label><input type="radio" ng-model="form.Program" name="Program" value="Other" required /> Other</label> 
    <input type="text" ng-model="OtherProgram" ng-disabled="form.Program != 'Other'" ng-change="form.OtherProgram = OtherProgram" ng-required="form.Program == 'Other'" name="Program_Other" /> 
    <input type="hidden" ng-model="form.OtherProgram" /> 
</p> 

然后在我的控制器此$手表功能:

$scope.$watch('form.Program', function (mVal) { 
    if (angular.isUndefined($scope.form)) return; 

    if (mVal === 'Other') { 
     $scope.form.OtherProgram = $scope.OtherProgram; 
    } else { 
     $scope.form.OtherProgram = null; 
    } 
}); 
相关问题