Dan*_*Dan 9 jquery angularjs diff2html
我试图使用格式化的角度指令内部的差异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);
})();
Run Code Online (Sandbox Code Playgroud)
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');
});
}
}
}]);
})();
Run Code Online (Sandbox Code Playgroud)
问题
运行时,我收到以下错误:
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;
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?我希望传递jQuery $会覆盖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));
})
}
}
}]);Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)