如何等待子指令渲染?

时间:2015-06-30 10:56:23

标签: javascript angularjs angularjs-directive

我有一个使用另一个指令的指令:

<div style="border:2px solid black;height:150px;padding:10px">
     <my-internal-directive></my-internal-directive>
     <my-internal-directive></my-internal-directive>
     <my-internal-directive></my-internal-directive>
</div>

内部指令:

<h2>foo</h2>

内部指令控制器:

internalDirectiveModule.directive('myInternalDirective', function($document){
    return {
      restrict:'E',
      scope: {},
      //templateUrl: 'myInternalDirective.html',    // EXTERNAL directive render first
      template: '<h2>foo</h2>',                     // INTERNAL directive render first
      link: function(scope, element){
        $document.find('body').append('<h1>internal directive\n');
      }  
    };
});

问题是当我使用templateUrl作为内部指令时,外部指令首先呈现,但是当我使用template时 - 内部指令首先呈现。我必须在内部指令(在调用link方法之后)内部从内部指令中获取数据,但我无法达到此行为,因为我认为仅使用templateUrl 。如何从父级的link方法中的renderred子指令中获取数据?

DEMO

3 个答案:

答案 0 :(得分:2)

而不是函数,将link设置为包含post函数的对象。

link: { post: function() {  }  }

post-linking-function documentation

答案 1 :(得分:0)

您可以尝试以下几点:

  1. 将内部指令的优先级设置为高于外部指令的优先级。
  2. 在超时之后触发外部指令的链接功能,如下所示:

    link:function(){$ timeout(linkFn,1000,false); }

  3. 更新: 以下是设置优先级的示例:

        angular.module('abc').directive('xyz', directive);
    
        directive.$inject = ['$timeout'];
    
        function directive($timeout) {
    
                return {
                        restrict: 'A',
                        priority: 100,
                        link: function ($scope, $element) {
    

答案 2 :(得分:0)

Sidharth&amp; Sons Arlen,你可以设置优先级或正常方式,如果你的代码中没有强制要求这个范围:{},那么在指令中使用双向数据绑定非常容易。 https://docs.angularjs.org/guide/directive