如何动态禁用Angular指令

How can I disable dynamically an Angular directive?

本文关键字:Angular 指令 动态 何动态      更新时间:2023-09-26

我正在使用AngularJS(HTML5/CSS3)进行一个项目。在我的项目的主html文件中,有一个表,我使用控制器的数组来填充:这个控制器管理html页面中包含该表的部分。

表格的html代码是这样的:

<table class="col-md-12 col-sm-12 col-lg-12 display" id="tableIdProcedures">
<thead>
    <tr>
        <th><span>CODE</span></th>
        <th><span>DESCRIPTION</span></th>
        <th><span>QUANTITY</span></th>
        <th><span>NOTE</span></th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="procedure in procedures">            
        <td>{{procedure.codExamination}}</td>
        <td>{{procedure.descrExamination}}</td>
        <td contenteditable="true">{{procedure.quantityExamination}}</td>
        <td>{{procedure.noteExamination}}</td>
    </tr>
</tbody>

控制器已正确填写表格。现在,问题是:如果它按下了页面的特定按钮,我想禁用表每行第三个单元格中的"contenteditable"指令,使字段不再可编辑。如何在javascript代码中禁用Angular指令?因此,如果我想重新启用这些字段,我该如何继续?

为了更好地理解"contenteditable"指令,我在这里复制了它的代码:

(function() {
'use strict';
angular.module('contenteditable', [])
        .directive('contenteditable', function($location) {
          return {
            require: 'ngModel',
            link: function(scope, element, attrs, ngModel) {
              element.bind('blur change', function() {
                scope.$apply(function() {
                  ngModel.$setViewValue(element.html());
                  // element.html contain the value modified
                  if($('#drugsSection').hasClass('ng-hide') === true){ 
                      // procedures active
                      calculateQuantityProcedures();
                  }else{
                      // drugs active
                      calculateQuantityDrugs();
                  }
                }); 
              });
              ngModel.$render = function() {
                element.html(ngModel.$viewValue);
              };
            }
          }
        })  
}());

提前感谢您的帮助。

您可以这样做:

当按下该按钮时,您可以在DOM中将contenteditable设置为false。所以

<td contenteditable="false">{{procedure.quantityExamination}}</td>

现在在您的指令中:

contenteditable 的值绑定$watch

 link: function(scope, element, attrs, ngModel) {
     scope.$watch(attrs.contenteditable, function(newval, oldval) {
         // unbind the events and disable the directive if its false
     });    
  }