簡體   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