【问题标题】:Make fields readonly in angular使字段以角度只读
【发布时间】:2016-01-15 20:22:31
【问题描述】:

我正在制作一个表单,用户可以通过单击添加更多按钮来添加更多字段。为此,我正在使用 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>

角度代码

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

【问题讨论】:

  • 可编辑的规则是什么?在添加新元素之前,总是最后一个元素是可编辑的?
  • @hansmaad 点击添加更多按钮不会添加新的,然后可以编辑,只读将适用于已经存在于数组中的那些
  • 哪个动作使新元素成为现有元素?单击添加一个我可以编辑的新项目,然后呢?是什么让这个项目成为只读的?
  • @hansmaad 我使用 Python 作为后端,所以当我从后端发送字段时,这些字段必须是只读的

标签: javascript angularjs


【解决方案1】:

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

您的 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
【解决方案2】:

我不确定您的确切用例,但您可以使用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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 2021-10-19
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    相关资源
    最近更新 更多