首页 文章

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

提问于
浏览
1

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

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

使用ng-repeat创建所有项目后,我需要用不同的线条填充每个画布 . 我试图在我的指令的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没有呈现相应的布局 . 我该如何重写代码?

2 回答

  • 1

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

    使用后链接功能:

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

    到post-link函数执行时,将呈现html .

相关问题