为ui.bootstrap.modal创建装饰器时出错 - modalWindow

时间:2013-12-25 12:06:54

标签: angularjs angular-ui

我正在尝试从ui.bootstrap.modal模块中修饰modalWindow指令。

这是我的代码:

angular.module('ui.bootstrap.modal').config(function($provide){

    $provide.decorator('modalWindowDirective', ['$delegate', '$timeout', function ($delegate, $timeout) {

        var directive = $delegate[0];


        directive.link = function(scope, element, attrs) {
            scope.windowClass = attrs.windowClass || '';

            /* this is what I added*/
            element.css('width', 'auto');
            element.css({ 'left': '50%', 'margin-left': -(element.width() / 2) + 'px' });
            /*----------*/

            //trigger CSS transitions
            $timeout(function () {
                scope.animate = true;
            });
        };
    }]);
});

当我这样做时,我收到了错误:

Raven: Exception TypeError: Cannot read property 'length' of undefined

即使我删除了装饰器的内容:

angular.module('ui.bootstrap.modal').config(function($provide){

    $provide.decorator('modalWindowDirective', ['$delegate', '$timeout', function ($delegate, $timeout) {


    }]);
});

我一直收到此错误

这是一个plnkr: http://plnkr.co/edit/x4p1MvZS7O4uEtB0qQC6

1 个答案:

答案 0 :(得分:3)

装饰时需要退回$delegate

此外,您需要装饰compile函数(并在其中,装饰link函数),而不是直接装饰directive.link函数。

PLUNKER

angular.module('ui.bootstrap.modal').config(function($provide){

  $provide.decorator('modalWindowDirective', ['$delegate', '$timeout', function ($delegate, $timeout) {

    var directive = $delegate[0];

    directive.compile = function(){
      return function (scope, element, attrs) {
        scope.windowClass = attrs.windowClass || '';
        console.log('TEST LOG');

        element.css('width', 'auto');
        element.css({ 'left': '50%', 'margin-left': -(element.width() / 2) + 'px' });

        //trigger CSS transitions
        $timeout(function () {
          scope.animate = true;
        });

      };
    }

    return $delegate;
  }]);
});

注意:您需要完整的jQuery才能使用element.width()