Angular。内部带有 ng-repeat 的自定义指令

Angular. Custom directive with ng-repeat inside

我有一个自定义指令,里面有 ng-repeat。 Ng-repeat 的模板看起来像

<div ng-repeat='(key, item) in items'>
    <canvas id='canvas-{{ key }}'></canvas>
</div>

使用 ng-repeat 创建所有项目后,我需要用不同的行填充每个 canvas。 我试图在我的指令的 link 功能中做到这一点:

link: function(scope, element) {
    scope.items = /* some data */
    $.each(items, function(key, item) {
        // some logic here with canvas like
        var drawingCanvas = document.getElementById('canvas-' + key);
        var context = drawingCanvas.getContext("2d");
        context.beginPath();
        context.moveTo(0, 0);
        context.lineTo(200, 100);
    });
}

但是我上面写的方式不行,因为当我调用$.each时,ng-repeat并没有渲染相应的布局。 我应该如何重写我的代码?

使用$timeout,这样就可以了。 $timeout 将强制执行一个 $digest cicle,这将触发 ngRepeat 指令强制它呈现结果。

$timeout(function(){
    scope.items = /* some data */
    $.each(items, function(key, item) {
        // some logic here with canvas like
        var drawingCanvas = document.getElementById('canvas-' + key);
        var context = drawingCanvas.getContext("2d");
        context.beginPath();
        context.moveTo(0, 0);
        context.lineTo(200, 100);
    });
},0);

使用post-link函数:

link: {
  pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  post: function postLink(scope, iElement, iAttrs, controller) { ... }
}

到 post-link 函数执行时,html 将被渲染。