This question already has answers here:
ng-model for `<input type=“file”/>` (with directive DEMO)
                                
                                    (12个答案)
                                
                        
                                2年前关闭。
            
                    
我正在从这样的后端接收JSON数据

{
  "data":{
    "xyz":[
      {
        "number":"1",
        "short_text":"Vertrag unterzeichnen",
        "long_text":"Nach Vertrabsunterzeichnung Namen eintragen",
        "is_photo":false
      },
      {
        "number":"2",
        "short_text":"HR unterrichten",
        "long_text":"HR hat eigene Workflows",
        "is_photo":true
      }
    ]
  }
}


在html中,我通过ng-repeat填充表单

<tr data-ng-repeat="choice in choices track  by $index">
    <td>{{choice.number}}</td>
    <td><p>{{choice.short_text}}</p></td>
    <td><input type="textbox" size="50" class="des-textinput" ng-model="choice.desc" required></td>
    <td><input type="checkbox"  ng-model="choice.include"></td>
    <td><input type="file" id="abc{{$index}}" class="photo-upload"
               file-model="pic{{$index}}" accept="image/*">
    </td>
</tr>


现在,如果我要接收的JSON中is_photo的值为true,我想使输入类型文件成为必需。对于每一行,如果is_photofalse的值,则将不需要此值。

根据给定的JSON,条件将是不需要第一个输入类型文件,因为第一行is_photofalse,但是第二个输入类型文件是必需的,因为is_photo的值是true

我该怎么做?

最佳答案

您可以使用“ ng-required”

对于文档,您可以阅读以下内容:https://docs.angularjs.org/api/ng/directive/ngRequired

像这样

<input name="myInput" ng-model="myInput" ng-required="myVar == 2">

//If photo is true required will be true else false
<input name="myInput" ng-model="myInput" ng-required="_photo">

<input name="myInput" ng-model="myInput" ng-required="choice.is_photo">

//Or use some function which returns boolean
<input name="myInput" ng-model="myInput" ng-required="isRequired(choice)">

//This is how you would use it with form and stop form from submittion
<form ng-app="myApp" ng-controller="validateCtrl"
      ng-init="isRequired=true"
      name="myForm" novalidate ng-submit="myForm.$valid && submit()">
        Username: <input type="text" name="user" ng-model="user"
                         ng-required="isRequired">
        Email : <input type="email" name="email" ng-model="email" required>
        <input type="submit" ng-click="isRequired=!isRequired;" />
</form>

    <script>
       var app = angular.module('myApp', []);
       app.controller('validateCtrl', function($scope) {
           $scope.user = 'John Doe';
           $scope.email = '[email protected]';
           $scope.submit = () => {console.log("s");}
       });
    </script>

关于javascript - 根据AngularJS中的条件使输入类型文件成为必需,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47304232/

10-10 13:13