在 browserify 中使用 jquery 插件以及 angular

using jquery plugin in browserify along with angular

我正在尝试使用名为 tipso 的工具提示插件。我使用 angular 和 browserify 作为我的依赖管理器。

除了这个插件,我的一切都很好。在 browserify 中,每一件小事都变得更加困难,但这似乎变成了一场噩梦。

我遵循了 tipso 的文档,它非常简单。但是当我 运行 应用程序时,我不断收到一条错误消息,指出 chrome 控制台中的 Uncaught TypeError: $(...).tipso is not a function

这是我的 broserify-shim 配置

   "browserify-shim": {
   "jquery": "$",
   "bootstrap": {
     "depends": [
       "jquery"
     ]
   },
   "tipso": {
       "depends": [
           "bootstrap"
       ]
    }
  }

我需要提示

var tipso = require('tipso');

这就是我初始化 tipso 的方式

//runs when DOM is completely loaded
angular.element(document).ready(function ($http, $rootScope) {    
    $('.tipso').tipso();
});

如有任何建议,我们将不胜感激。

如果您按照错误 $(...).tipso 使用它,并且根据您的 Browserify Shim 配置要求 jQuery 作为 $,我假设 Tipso 是jQuery 插件。你需要指定它依赖于 jQuery,像这样:

 "browserify-shim": {
   "jquery": "$",
   "bootstrap": {
     "depends": [
       "jquery"
     ]
   },
   "tipso": {
       "depends": [
           "jquery",
           "bootstrap"
       ],
    "exports": "$.fn.tipso"
    }
  }

我终于弄明白了,希望对大家有所帮助。

  1. 诀窍是在全局范围内公开 jQuery(我知道我不应该这样做,替代方法是在我希望插件工作的任何地方公开它).

    global.$ = global.jQuery = require('jquery');
    
  2. 完成后,我们将制定一个 Angular 指令

    rootModule.directive('cooltip', function () {
      return {
          restrict: 'A',
          link: function (scope, element, attributes) {
              $(element).tipso({
                  position: 'right',
                  delay: 600
            });
          }
       };
    });
    
  3. 使用此指令将 jQuery 插件的属性应用于 html

    中的元素
    <button cooltip class="btn"> Hover over me </button>
    

根据 jQuery 插件及其功能决定指令类型(元素、属性、注释等)。