繁体   English   中英

角。 内置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创建所有项目后,我需要用不同的线条填充每个画布。 我试图在我的指令的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);

使用后链接功能:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM