在带有Noconflict的角指令中运行jQuery插件DIFF2HTML



我正在尝试使用diff2html和 var jq = $.noConflict();

在角度指令中格式化一个差异

我已经创建了一个角质常数来持有jQuery并将其传递到指令中:

app.js

(function () { //IIFE to enable strict mode
    'use strict';
    angular.module('dashboard', ['ui.router', 'ngSanitize'])
        .config(['$interpolateProvider', function ($interpolateProvider) {
            $interpolateProvider.startSymbol('[[[').endSymbol(']]]');
        }])
        .constant('jQuery', window.jQuery);
})();

指令.js

(function () { //IIFE to enable strict mode
    'use strict';
    angular.module('dashboard')
        .directive("loadDiff", ['$http', 'jQuery', function($http, $) {
            return {
                restrict: "A",
                link: function(scope, elem, attrs) {
                    $http.get("diff url here").success(function (data) {
                        var diff2htmlUi = new Diff2HtmlUI({diff: data});
                        diff2htmlUi.draw('#line-by-line');
                    });
                }
            }
        }]);
})();

问题

运行时,我会收到以下错误:

TypeError: $ is not a function at Diff2HtmlUI._initSelection at new Diff2HtmlUI

调试此问题,您可以看到,当Diff2HtmlUI实例化时,它会试图设置身体,并且由于与var jq = $.noConflict();的冲突,这可能会失败。

  Diff2HtmlUI.prototype._initSelection = function() {
    var body = $('body');
    var that = this;

如何解决此问题?我希望通过$覆盖Noconflict冲突?

我真的不知道为什么您将jQuery传递给您的指示。由于您直接加载了它,因此您和diff2html已经可以通过全局window对象访问它。

另外,您可能只想传递指令element,而不是外部DIV ID,只需将其作为$(elem)传递,因为它期望jQuery对象或DOM查询字符串。

angular.module('dashboard', [])
  .config(['$interpolateProvider', function ($interpolateProvider) {
    $interpolateProvider.startSymbol('[[[').endSymbol(']]]');
  }])
  .constant('jQuery', window.jQuery)
  .directive('loadDiff', ['$http', function ($http) {
    return {
      restrict: 'A',
      link: function (scope, elem, attrs) {
        $http({
          url: 'https://api.github.com/repos/rtfpessoa/diff2html/pulls/106.diff',
          headers: {
            accept: 'application/vnd.github.v3.diff'
          }
        })
        .then(function (resp) {
          var diff2htmlUi = new Diff2HtmlUI({ diff: resp.data });
          diff2htmlUi.draw($(elem));
        })
          
      }
    }
  }]);
<html>
  <head>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/diff2html/2.3.0/diff2html.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/diff2html/2.3.0/diff2html.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/diff2html/2.3.0/diff2html-ui.js"></script>
    <script data-require="angular.js@1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
    <script data-require="jquery@3.1.1" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  </head>
  <body ng-app="dashboard">
    <div load-diff="load-diff">Loading diff...</div>
  </body>
  
</html>

相关内容

  • 没有找到相关文章

最新更新