【问题标题】:Is it possible to have a Parent Directive define a function, execute it before the child directive's template attribute calls that function?是否可以让父指令定义一个函数,在子指令的模板属性调用该函数之前执行它?
【发布时间】:2017-12-09 21:37:16
【问题描述】:

我对 Angular 还很陌生,可以使用一些关于加载顺序的帮助。

我有两个指令。一个父指令 (resume-list) 和一个子指令 (slick-slider)。我的问题是子指令的属性 (data-source-fn) 在定义该 fn 的父控制器之前执行。这会导致控制台中出现错误 =“可能未处理的拒绝:未定义” - 并且滑动滑块的幻灯片永远不会加载:

<resume-list>
    <slick-slider
      data-page-size="3"
      data-scroll-size="3"
      data-page-buffer="3 + 1"
      data-total="slides.length"
      data-config="resumeConfig"
      data-theme="'theme-resume'"
      data-slide-template-url="'app/widgets/slickSlider/resume-slide-tpl.html'"
      data-source-fn="getResumeSlides(id, start, limit)">
    </slick-slider>
</resume-list>

现在我尝试了三种不同的方法来解决这个问题,但总是遇到同样的错误。 但是,当我使用打字稿将父指令制作成组件时 - 一切正常。所以,我的问题是......是否可以将父指令作为具有要传递的数据的指令是孩子吗?

我为父指令所做的尝试:

 1. Directive with Controller
 2. Directive with no Controller but a (pre) link function instead
 3. Directive with no Controller and a compile (pre) link function

以上所有三个都给我同样的错误:“可能未处理的拒绝:未定义” ....当我在控制台中调试时,未定义的对象最终成为 data-source-fn...

【问题讨论】:

标签: angularjs angularjs-directive angularjs-scope angular-controller


【解决方案1】:

依赖于存在绑定的初始化逻辑应该放在控制器的$onInit() 方法中,保证总是在绑定分配后调用。

app.component('myComponent', {
  bindings: {value: '<'},
  controller: function() {
    this.$onInit = function() {
      // `this.value` will always be initialized,
      this.doubleValue = this.value * 2;
    };
  }
})

作为指令:

app.directive('myDirective', {
  scope: {value: '<'},
  controller: function($scope) {
    this.$onInit = function() {
      // `$scope.value` will always be initialized,
      $scope.doubleValue = $scope.value * 2;
    };
  }
})

【讨论】:

  • 嗨,乔治,感谢您的回复。我知道可以作为一个组件来做。我的问题是,是否可以作为指令执行?在我的工作中,我将它创建为一个组件......他们希望它作为一个指令。我尝试了三种不同的方式来实现指令,它们的加载方式与组件不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多