Make read-only fields in angular

I am making a form where the user can add more fields by clicking the add button yet. for this I use ng-repeat, and when the user clicks the "Add more" button, one field is placed in the array in the results of ng-repeat in another field.

Now, for some cases, the ng-repeat array may contain some fields, I want to make them read-only, but if the user clicks the Add More button, then this field may be editable. My code is:

HTML code

 <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 code

$scope.add_extra_field = function(){
    $scope.ui_fields.push({ 
        name: "",
        type: ""
      });
    }
+4
source share
2 answers

Use an extra field isreadonlyin the array ui_fieldsand ngReadOnly , for example:

Your 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>

Your javascript:

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

, 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" />

Edit: 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;
}
+1

All Articles