使用 ng-disabled 禁用 table 内的所有表单元素

Disable all form elements inside table with ng-disabled

有没有办法用ng-disabled禁用整个table?

fiddle

$scope.isDisabled = false;
$scope.disableClick = function() {
  $scope.isDisabled = true;
}

根据 Angular 的 ng-disabled 文档,它只能用于 INPUT 元素。参见 - ng-disabled

所以在table上使用这个标签不会有任何效果。 如果您想禁用 table 中的每个元素,您可以对每个元素使用 ng-disabled。

至于使 table "not clickable" 考虑为元素定义自定义 CSS class 并使用 ng-class 动态分配 class 当你想要的时候。

CSS 用于禁用文本选择:

.myClass {
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
}

参见 -

Related post

ngClass documentatin

有一种方法可以做到这一点,因此您可以在 table(或任何元素,就此而言)上使用 ng-disabled 属性,并保留任何表单元素的所有标记里面没有变化:

<table ng-disabled="disabled">
  <tbody>
    <tr>
      <td><input type="text"></td>
      <td><button>A button</button></td>
      <td>
        <select>
          <option>An option</option>
          <option>Another option</option>
        </select>
      </td>
      <td>
        <textarea>Textarea</textarea>
      </td>
    </tr>
  </tbody>
</table>

您可以扩展 Angular 的 ngDisabled 指令,以在控制器上公开其 ng-disabled 属性中的值:

app.directive('ngDisabled', function() {
  return {
    controller: function($scope, $attrs) {
      var self = this;
      $scope.$watch($attrs.ngDisabled, function(isDisabled) {
        self.isDisabled = isDisabled;
      });      
    }
  };
});

然后您可以从其中的任何 inputselectbuttontextarea 元素访问控制器的 isDisabled 属性,创建观察者每个:

function reactToParentNgDisabled(tagName) {
  app.directive(tagName, function() {
    return {
      restrict: 'E',
      require: '?^ngDisabled',
      link: function(scope, element, attrs, ngDisabledController) {
        if (!ngDisabledController) return;
        scope.$watch(function() {
          return ngDisabledController.isDisabled;
        }, function(isDisabled) {
          element.prop('disabled', isDisabled);
        });
      }
    };
  });   
}

['input', 'select', 'button', 'textarea'].forEach(reactToParentNgDisabled);

你可以see this working in this Plunker

虽然我不能说它的效率:<table> 上的元素会有一个观察者,然后 table.[=26= 中的每个表单元素都有一个额外的观察者]

我确实考虑过单个 watch + 范围事件,但我遇到了一个问题,因为具有 ng-disabled 属性的元素可能与 parent/sibling 元素共享其范围,因此任何范围事件它广播可以发送到它之外的元素。

或者,为了消除对每个表单元素的观察者的需要,扩展 ngDisabled 指令的控制器可以在其中维护一个表单元素列表,并更改它们的所有 [=一次 24=] 个属性。