You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何动态修改表格单元格的ng-readonly属性?

Fixing ng-readonly in Angular the Right Way

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:

  1. Bind ng-readonly to 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>
    
  2. 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 its isReadonly property:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:40:02