角。内置ng-repeat的自定义指令

时间:2015-01-08 11:40:53

标签: angularjs angularjs-directive html5-canvas

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

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

使用ng-repeat创建所有项目后,我需要用不同的线条填充每个画布。 我试过在我的指令的链接功能中做到这一点:

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没有呈现相应的布局。 我应该如何重写我的代码?

2 个答案:

答案 0 :(得分:2)

使用$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);

答案 1 :(得分:1)

使用后链接功能:

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

当执行post-link函数时,将呈现html。

相关问题