我正在尝试使用diff2html和var jq = $.noConflict();
我创建了一个Angular常量来保存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);
})();
directive.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冲突?
答案 0 :(得分: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>
&#13;