Search code examples
angularjsreadonly-attribute

Setting readonly using ng-readonly dynamically is not working


I am fetching some data from the database server and displaying the same in tabular format on my GUI. I want to achieve the following in my GUI design

(a) Any cell in the table should be editable except the first column in the table. (b) The first row of the table, if added newly to the GUI for accepting new inputs from the user, should be exempted from the above rule i.e., all columns of the first row should be editable.

To achieve this I wrote the following code.

HTML Code

    <tbody>
           <tr ng-repeat="x in sensordata">
           <td>
             <input class="form-control" type="text" ng-model="x.name" placeholder="Sensor name" ng-readonly="namereadonly" ng-init="ctrl2.setReadOnly(x.name,$index)"/>
           </td>
           <td>
              <input class="form-control" type="text" ng-model="x.unit" placeholder="Measurement Unit" required/>
           </td>
           <td>
                <input class="form-control" type="text" ng-model="x.type" placeholder="Sensor Type" required/>
           </td>
           <td>
                <input class="form-control" type="text" ng-model="x.periodicity" placeholder="Periodicity" required/>
           </td>
           <td>
                <input class="form-control" type="text" ng-model="x.formula" placeholder="Formula" required/>
           </td>
           <td>
               <input class="form-control" type="email" ng-model="x.vendor" placeholder="Email Id" required/>
           </td>
           </tr>
   </tbody>

Controller code is as follows.

this.setReadOnly = function(name,idx) {
        console.log('name ' + name + ' idx ' + idx);
        if (name === undefined || name === null || name === '') $scope.namereadonly = false;
        if (name !== '' || name !== undefined || name !== null) $scope.namereadonly = true;
    };

When I am executing above code the first column of all the rows are getting uneditable as expected. But when I am adding new row to the (by adding new empty JSON object in the sensordata array in another function of the same controller) GUI, the first column of the row is getting uneditable which should not be the case as per the first if statement in the above method. I am unable to figure out why it is happening.


Solution

  • <input class="form-control" type="text" ng-model="x.name" placeholder="Sensor name" ng-model-options="{ updateOn: 'blur' }" ng-readonly="x.name.length"/> this line solved my problem. Without ng-model-options attribute as soon as one types a character in the newly added row the first column is becoming uneditable. With ng-model-options this issue is resolved as now the column would become uneditable upon moving focus from the input field.

    No method is to be written in the controller.