在Angular中将字段设置为只读

4

我正在制作一个表单,用户可以通过点击添加更多按钮来添加更多字段。为此,我使用ng-repeat,当用户点击添加更多按钮时,一个字段被推送到ng-repeat数组中,从而导致另一个字段。

现在对于某些情况,ng-repeat数组可能包含一些字段,我想将它们设置为只读,但如果用户点击添加更多按钮,则该字段可以编辑。 我的代码:

HTML代码

 <div ng-repeat="field in ui_fields">
     <label for="Language">Field Name :</label><input class="form-control" type="text" ng-model="field.name">
     <label for="Language">Field type :</label>
     <select class="form-control" ng-model="field.type">
         <option value="">Select field type</option>
         <option value="timedate">Date & Time</option>
         <option value="text">Text</option>
     </select>
 </div>

Angular 代码

$scope.add_extra_field = function(){
    $scope.ui_fields.push({ 
        name: "",
        type: ""
      });
    }

可编辑的规则是什么?始终只有最后一个元素是可编辑的,直到添加新元素为止吗? - hansmaad
@hansmaad 如果通过单击“添加更多”按钮没有添加新的,则可以对其进行编辑,如果它们已经存在于数组中,则将应用只读。 - n.imp
哪个操作会使新元素变成现有元素?点击添加一个我可以编辑的新项目,然后呢?是什么让这个项目只读? - hansmaad
@hansmaad 我正在使用Python作为后端,因此当我从后端发送字段时,这些字段必须是只读的。 - n.imp
2个回答

5

ui_fields数组中使用额外的字段isreadonlyngReadOnly指令,例如:

你的HTML代码:

<div ng-repeat="field in ui_fields">
    <label for="Language">Field Name :</label><input class="form-control" ng-readonly="field.isreadonly" type="text" ng-model="field.name">
    <label for="Language">Field type :</label>
    <select class="form-control"  ng-disabled="field.isreadonly" ng-model="field.type">
        <option value="">Select field type</option>
        <option value="timedate">Date & Time</option>
        <option value="text">Text</option>
    </select>
</div>

您的 JavaScript 代码:

$scope.add_extra_field = function(){
    $scope.ui_fields.push({ 
        name: "",
        type: "",
        isreadonly: false
      });
    }

它运行良好,谢谢。但是在选择类型的情况下,应该使用 ng-disabled 而不是 ng-readonly - n.imp

1
我不确定你的确切用例,但是您可以使用ngReadonly来使控件有条件地只读。在这个例子中,我将最后一行设置为只读:

http://plnkr.co/edit/sZhKsjWoFBh30ikKZeN8?p=preview

<input class="form-control" type="text" 
       ng-model="field.name" ng-readonly="$index < ui_fields.length - 1" />

编辑: 我进行了分支以符合您的实际用例 http://plnkr.co/edit/DT7oMAhkjGxGa1GRN5uP?p=preview

在保存函数中,您可以设置上次保存数据的索引以将编辑后的数据发送到服务器。使用此索引作为ngReadonly的条件。

<input class="form-control" type="text" 
       ng-model="field.name" ng-readonly="$index <= savedIndex" />

控制器:

$scope.add_extra_field = function(){
  $scope.ui_fields.push({ 
      name: "",
      type: ""
    });
  }
$scope.save = function() {
   // send to server
   $scope.savedIndex = $scope.ui_fields.length -1;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接