9

我正在尝试使用diff2htmlvar jq = $.noConflict();

我创建了一个 Angular 常量来保存 jQuery,并将其传递给指令,如下所示:

应用程序.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;

我该如何解决这个问题?我希望通过 jQuery$来覆盖 noconflict 冲突?

4

1 回答 1

1

我真的不明白你为什么要传递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>

于 2017-05-08T03:26:00.387 回答