CodeQL 文档

双重编译

ID: js/angular/double-compilation
Kind: problem
Security severity: 8.8
Severity: warning
Precision: very-high
Tags:
   - reliability
   - frameworks/angularjs
   - security
   - external/cwe/cwe-1176
Query suites:
   - javascript-code-scanning.qls
   - javascript-security-extended.qls
   - javascript-security-and-quality.qls

点击查看 CodeQL 仓库中的查询

AngularJS 编译器处理(部分)DOM,确定哪些指令与哪些 DOM 元素匹配,然后将指令应用于元素。每个 DOM 元素应该只编译一次,否则可能会导致意外行为。

建议

只编译新的 DOM 元素。

示例

以下示例(改编自 AngularJS 开发人员指南)显示了一个指令,它为 DOM 元素添加了一个工具提示,然后编译整个元素以应用嵌套指令。

angular.module('myapp')
       .directive('addToolTip', function($compile) {
  return {
    link: function(scope, element, attrs) {
      var tooltip = angular.element('<span ng-show="showToolTip">A tooltip</span>');
      tooltip.on('mouseenter mouseleave', function() {
        scope.$apply('showToolTip = !showToolTip');
      });
      element.append(tooltip);
      $compile(element)(scope); // NOT OK
    }
  };
});

这是有问题的,因为它会重新编译整个 element,包括已经编译的部分。

相反,应该只编译新元素

angular.module('myapp')
       .directive('addToolTip', function($compile) {
  return {
    link: function(scope, element, attrs) {
      var tooltip = angular.element('<span ng-show="showToolTip">A tooltip</span>');
      tooltip.on('mouseenter mouseleave', function() {
        scope.$apply('showToolTip = !showToolTip');
      });
      element.append(tooltip);
      $compile(tooltip)(scope); // OK
    }
  };
});

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私