using jquery plugin in browserify along with angular

蓝咒 提交于 2020-01-15 10:15:27

问题


I am trying to use a tooltip plugin called tipso. And I am using angular along with browserify as my dependency manager.

I have everything working out for me except for this plugin. Every little thing is little harder in browserify but this one seems to be turning into a nightmare.

I have followed the documentation of tipso which is pretty simple. But when I run the app, I keep getting an error message stating that Uncaught TypeError: $(...).tipso is not a function in the chrome console.

This is my broserify-shim config

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

I have required tipso

var tipso = require('tipso');

This is how I have initialized tipso

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

Any suggestion will be appreciated.


回答1:


I finally figured it out, I hope this helps someone.

  1. The trick is to expose jQuery in the global scope (I know I am not supposed to do this and the alternative for this is to expose it wherever I want the plugin to work).

    global.$ = global.jQuery = require('jquery');
    
  2. Once that is done, we'll make an Angular directive

    rootModule.directive('cooltip', function () {
      return {
          restrict: 'A',
          link: function (scope, element, attributes) {
              $(element).tipso({
                  position: 'right',
                  delay: 600
            });
          }
       };
    });
    
  3. Use this directive to use apply the jQuery plugin's properties on an element in html

    <button cooltip class="btn"> Hover over me </button>
    

Depending on the jQuery plugin and it;s funtionality decide on the directive type (Element, Attribute, Comment etc).




回答2:


If you're using it like $(...).tipso per the error, and you're requiring jQuery as $ per your Browserify Shim config, I'm assuming Tipso is a jQuery plugin. You need to specify that this it depends on jQuery, like so:

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


来源:https://stackoverflow.com/questions/36939784/using-jquery-plugin-in-browserify-along-with-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!