2

I am using AngularJS 1.2 and trying to include a jQuery plugin via an Angular Directive. As an example I have chosen a plugin called spectrum. I have not included (and do not wish to include) jQuery separately, as AngularJS is said to include jqLite, a smaller version of jQuery.

myDirs.directive('spectrumDir', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            angular.element(element).spectrum(scope.$eval(attrs.spectrumDir));
        }
    };
});

However, when i try to load the app, I get:

Uncaught ReferenceError: jQuery is not defined spectrum.js:1888 (anonymous function)

The error stems from the initialization of the plugin:

(function (window, $, undefined) {
    …code…
})(window, jQuery);

What is the generic solution to including jQuery plugins in AngularJS? Is there any elegant way to achieve this without including the full jQuery library?

AngularJS comes bundled with a lite implementation of jQuery referred to as jqLite. For Angular’s purposes, this is effectively jQuery, albeit an extremely gutted one. The creators of Angular believe the jqLite API to be sufficient for nearly every application if utilized properly.

4

2 回答 2

2

正如“Arun P Johny”所说,您必须首先包含 jquery javascript,然后包含依赖于 jQuery 的插件

于 2013-10-16T15:01:07.533 回答
1

你想要做的是在插件中而不是(window,jQuery)导出jqLit​​e,它是angular.element。所以 (window, angular.element);

或者在初始化你的 Angular 应用之前更容易添加 window.jQuery = window.$ = angular.element;

作为主脚本文件中的第一行 js,如果插件不使用 jqLit​​e 未涵盖的任何方法,那么你很幸运!否则,可能包括 Zepto 作为轻量级 jquery 替代方案并在插件返回(窗口,Zepto)中;

于 2013-12-20T10:21:42.377 回答