【问题标题】:AngularJS angular-ui-calendar TypeError: this.$compile is not a function; this.$compile has value when inside $onInit(), but undefined when outsideAngularJS angular-ui-calendar TypeError: this.$compile 不是函数; this.$compile 在 $onInit() 内部时具有值,但在外部时未定义
【发布时间】:2018-11-23 16:59:05
【问题描述】:

在我的构造函数中我通过了:

constructor($compile, uiCalendarConfig) {
    'ngInject';

    this.$compile = $compile;
    this.uiCalendarConfig = uiCalendarConfig;
}

当我在 $onInit() 的开头记录它的值时

$onInit() {
    console.log('this.$compile:', this.$compile, 'this.uiCalendarConfig:', this.uiCalendarConfig);
...
}

我得到 $compile 函数的文字代码。

但是当从内部调用 $compile 时

eventRender( event, element, view ) {
  element.attr({'tooltip': event.title,
    'tooltip-append-to-body': true});
  console.log('event:', event);
  console.log('edited element:', element);
  console.log('view:', view);
  console.log('this.$compile:', this.$compile);
  this.$compile(element)(this);
};

里面提到的:

this.uiConfig = {
      calendar: {
        height: 450,
        editable: true,
        header:{
          left: 'title',
          center: '',
          right: 'today, prev, next'
        },
        eventClick: this.alertOnEventClick,
        eventDrop: this.alertOnDrop,
        eventResize: this.alertOnResize,
        eventRender: this.eventRender
      }
};

console.log('this.$compile:', this.$compile); 的结果是 undefined this.$compile 的值。

这是我的问题,因为我不知道为什么它在那里没有定义,如果在控制器的初始化它已经是一个函数。

有人知道我可能会错过什么吗?

【问题讨论】:

    标签: javascript angularjs compilation initialization angular-calendar


    【解决方案1】:

    那是因为eventRender 是在uiConfig 的上下文中调用的,而在那个上下文中我猜没有$compile!我想到的一种补救方法是存储控制器的引用并在 eventRender 函数中使用它。

    var self = this;
    
    eventRender( event, element, view ) {
      element.attr({'tooltip': event.title,
        'tooltip-append-to-body': true});
      console.log('event:', event);
      console.log('edited element:', element);
      console.log('view:', view);
      console.log('this.$compile:', this.$compile);
      self.$compile(element)(this);
    };
    

    我没有测试过,可能根本不起作用。

    【讨论】:

    • 它有效,但是当放在构造函数中时:constructor($compile, uiCalendarConfig) { 'ngInject'; const self = this; this.$compile = $compile; this.uiCalendarConfig = uiCalendarConfig; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2019-04-27
    • 2022-01-03
    相关资源
    最近更新 更多