Angular指令只是动态加载jQuery插件(pickadate)的一部分

时间:2015-04-10 14:41:40

标签: angularjs jquery-plugins angularjs-directive pickadate

我有一个ng-repeat渲染指令,因为ng-repeat的长度未知我尝试通过指令动态加载jquery插件。

我相信我非常接近,但是,只有部分插件加载,不幸的是没有给出任何错误。对于那些熟悉Pickadate插件的人来说,这些类是在input元素上呈现的,但是它动态附加的元素不会在点击时呈现。

这是我的代码:

HTML

<div class="calendar" add-calendar>Click to add calendar</div>

Angular Directive 1

agentApp.directive('addCalendar', ['$compile', function($compile) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {

            template = '<input type="text" jq-date-picker-range />';

            element.bind('click', function() {
                angular.element(this).after($compile(template)(scope));
            });
        }
    }
}]);

Angular Directive 2

agentApp.directive('jqDatePickerRange', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          angular.element(element).pickadate();
        }
    };
});

输出

<input type="text" jq-date-picker-range class="ng-scope picker__input picker__input--active" readonly="" id="P780839543" aria-haspopup="true" aria-expanded="true" aria-readonly="false" aria-owns="P780839543_root">

正如您所看到的,正在编写类,但之后呈现的日历div元素不会这样做。

非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:1)

看起来问题是渲染问题。实际上,我假设负责渲染的线程在进行初始调用时很忙,因此插件可以将类添加到现有DOM元素,但是向DOM添加新元素则不然。我认为这比这个解决方案更好 - 而且我喜欢听到它。但是现在,将调用包装在$ timeout函数中可以解决问题。

agentApp.directive('jqDatePickerRange', ['$timeout', function($timeout) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {

          $timeout(function() {
            angular.element(element).pickadate();
          }, 0);

        }
    };
}]);