繁体   English   中英

来自jQuery插件的angularjs指令

[英]angularjs directive from jquery plugin

在查看了Angularjs的文档后,我希望有人可以帮助澄清我面临的问题。 我正在寻找写一个包含jQuery插件的指令,但是我不确定这种最佳实践。 从本质上讲,这是使jquery插件与angular很好地玩并使其更加参数化和可扩展的移植。

我要移植的插件主要是用于处理表单的DOM操作(就像大多数jQuery库一样)。 如果需要,我可以发布更多代码,但是我主要想知道将其构建为有角度的最佳实践或注意事项。

谢谢!!

到目前为止,我的指令:

“使用严格”;

/**
 * @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
      };

  };
});

如果插件非常简单并且没有任何回调,则代码非常简单:

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

但是,如果插件具有任何自定义事件或回调,则需要将它们包装在$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');
            });
        }
    };
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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