求助:如何动态修改表格单元格的ng-readonly属性?
Hey there! I see you're trying to toggle the ng-readonly state on table cells by directly manipulating the DOM, and you're right—this approach won't work as expected with Angular. Let me break down why, and show you a much simpler, Angular-friendly way to handle this.
Why Your Current Code Isn't Working
Angular relies on its scope and change detection system to update the DOM. When you use cells.attr("ng-readonly", "false"), you're modifying the raw DOM attribute after Angular has already compiled and linked the template. Angular doesn't monitor raw attribute changes like this, so your change won't trigger any updates to the input's readonly state.
The Simple, Angular-Approved Method
Instead of touching the DOM directly, use a scope variable to bind to ng-readonly. Here's how:
Bind
ng-readonlyto a scope variable in your template
If you're targeting all cells, use a single scope variable:<table> <tr> <td><input type="text" ng-readonly="cellIsReadonly"></td> <!-- More cells here --> </tr> </table>If you need to control individual cells (e.g., in an
ng-repeat), use a variable per item:<table> <tr ng-repeat="row in tableRows"> <td><input type="text" ng-readonly="row.isReadonly"></td> </tr> </table>Update the scope variable in your controller
For the global case, just toggle the scope variable directly in your event handler:// Inside your controller or event handler $scope.cellIsReadonly = false; // If you're running this code outside Angular's context (e.g., a native JS event), wrap it in $apply: // $scope.$apply(() => { // $scope.cellIsReadonly = false; // });For individual rows (with
ng-repeat), find the corresponding row data and update itsisReadonlyproperty:// Assuming e.currentTarget maps to a row, get its index or reference to the row data const rowIndex = angular.element(e.currentTarget).closest('tr').index(); $scope.tableRows[rowIndex].isReadonly = false;
This way, Angular's change detection will automatically pick up the variable change and update the input's readonly state—no manual DOM manipulation needed!
内容的提问来源于stack exchange,提问作者Soham Banerjee

