Angularjs 使用ng readonly动态设置readonly无效
我正在从数据库服务器获取一些数据,并在GUI上以表格格式显示这些数据。我想在我的GUI设计中实现以下目标 (a) 除表中的第一列外,表中的任何单元格都应可编辑。 (b) 如果表格的第一行新添加到GUI以接受用户的新输入,则应不受上述规则的约束,即第一行的所有列都应可编辑 为了实现这一点,我编写了以下代码 HTML代码Angularjs 使用ng readonly动态设置readonly无效,angularjs,readonly-attribute,Angularjs,Readonly Attribute,我正在从数据库服务器获取一些数据,并在GUI上以表格格式显示这些数据。我想在我的GUI设计中实现以下目标 (a) 除表中的第一列外,表中的任何单元格都应可编辑。 (b) 如果表格的第一行新添加到GUI以接受用户的新输入,则应不受上述规则的约束,即第一行的所有列都应可编辑 为了实现这一点,我编写了以下代码 HTML代码 <tbody> <tr ng-repeat="x in sensordata"> <td>
<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>
当我执行上述代码时,所有行的第一列将变得不可编辑。但是,当我向GUI添加新行(通过在同一控制器的另一个函数中的sensordata数组中添加新的空JSON对象)时,该行的第一列变得不可编辑,这与上述方法中的第一个if语句不同。我无法理解为什么会发生这种情况。您可以尝试
if-else
语句,该语句可以正确设置变量
this.setReadOnly = function(name,idx) {
console.log('name ' + name + ' idx ' + idx);
if (name === undefined || name === null || name === '') $scope.namereadonly = false;
else (name !== '' || name !== undefined || name !== null) $scope.namereadonly = true;
};
a) 除表中的第一列外,表中的任何单元格都应可编辑
桌子。(b) 表的第一行(如果新添加到GUI)
对于接受用户的新输入,应免除
上述规则,即第一行的所有列都应该是可编辑的
有很多解决方案,但这取决于你/你的需要。在这里,我想与大家分享两个逻辑:
- 为用户输入的新对象添加新键,并使用此新键将它们与旧对象区分开来
,新对象应具有此键:ng readonly=“x.new”
{name:,new:true}
- 存储主数组的长度,并使用它区分输入的新对象
,mainlength类似于:ng readonly=“$index
(angular.copy的使用)请参阅$scope.mainlength=angular.copy($scope.sensordata.length)
<input class="form-control" type="text" ng-model="x.name" placeholder="Sensor name" ng-readonly="{{x.name !== '' && x.name !== undefined && x.name !== null}}" />
这一行解决了我的问题。如果没有ng模型选项属性,则在新添加的行中键入字符后,第一列将变得不可编辑。使用ng模型选项解决了这个问题,因为现在在从输入字段移动焦点时,列将变得不可编辑
不在控制器中写入任何方法。当我将if语句更改为“if(name==undefined | | | name===null | | name====''{$scope.idx=false;}和if(name!=''| | name!==undefined | name!==null){$scope.idx=true;console.log('readonly')}和ng readonly=“$index”时,问题已得到部分纠正。这可能是独立处理每个输入元素的readonly属性。但是,现在,表的第一行的第一列变成了可编辑的,而它应该是不可编辑的,因为我还没有将新行添加到GUI中。如果您将它作为FIDLE共享,这会很有帮助
<input class="form-control" type="text" ng-model="x.name" placeholder="Sensor name" ng-readonly="{{x.name !== '' && x.name !== undefined && x.name !== null}}" />