简体   繁体   中英

angularjs directive from jquery plugin

After looking through docs for Angularjs, I was hoping someone could help clarify an issue I'm facing. I'm looking to write a directive that incorporates a jQuery plugin, but I'm not sure of a best practice for something like this. It's essentially a port-over to make a jquery plugin play nicely with angular and make it more parameterized and extensible.

The plugin I'm looking to port is mainly DOM manipulation (like most jQuery libraries) to handle forms; I can post further code if necessary, but I'm mainly wondering about best practices or things to watch out for when building it into angular.

Thanks!!

my directive so far:

'use strict';

/**
 * @ngdoc directive
 * @name goodStewardApp.directive:card
 * @description
 * # card
 */
angular.module('goodStewardApp')
  .directive('card', function() {
    return {
      template: "<card> What is this madness? </card>",
      restrict: 'A',
      link: function() {
        // jQuery function here
      };

  };
});

If the plugin is very simple and does not have any callbacks then the code is very simple:

angular.module('goodStewardApp').directive('card', function() {
    return {
        template: "<card> What is this madness? </card>",
        restrict: 'A',
        link : function(scope, element, attr) {
            $(element).plugin();
        }
    };
});

If, however, plugin has any custom events or callbacks, then you need to wrap them in $apply() :

angular.module('goodStewardApp').directive('datepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            var options = scope.$eval(attrs['datepicker']);

            $(function () {
                element.datepicker({
                    dateFormat: options['dateFormat'],
                    onSelect: function (date) {
                        scope.$apply(function () {
                            ngModelCtrl.$setViewValue(date);
                        });
                    }
                }).prop('readonly', true).addClass('datepicker');
            });
        }
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM