AngularJS ng-repeat:在循环内动态渲染/绑定画布

时间:2016-09-29 04:43:45

标签: javascript angularjs canvas angularjs-directive

AngularJS的世界相对较新,到目前为止享受它。
但是,我正在努力尝试遍历我的数据库中的条目并为每个条目渲染<canvas>

说这是我的数据(为简洁起见缩短):

var paintings = [
    { "_id" : ObjectId("31c75"), "data" : "0,0,0,0" },
    { "_id" : ObjectId("deadb"), "data" : "1,3,0,255" }
];

由工厂加载到控制器中:

app.factory('paintings', ['$http', function($http) {
    var o = {
        paintings: []
    };
    o.getAll = function() {
        return $http.get('/paintings')
            .success(function(data) {
                angular.copy(data, o.paintings);
            });
    }
    return o;
}]);

我想遍历每个条目并构造一个<canvas>元素,然后将<canvas>元素传递给另一个以Grid为参数的对象(data) ,创建上下文并根据数据绘制<canvas>

简单,对吧?不幸的是,我对如何这样做感到茫然,并且没有语言可以提出更尖锐的问题。
我认为存在的问题是我使用的内联模板不是然后呈现。

这通常是我目前正在尝试的方法:

HTML:

<div ng-repeat="painting in paintings" some-directive-maybe="bindCanvas(painting._id)">
    <canvas id="{{ painting._id }}" width="800" height="400"></canvas>
</div>

JS:

app.controller('PaintingCtrl', [
    '$scope',
    function($scope) {
        $scope.bindCanvas(canvasId) {
            var grid = new Grid(document.getElementById(canvasId));
            // Have fun with grid
        }
    }
]);

帮帮我,StackOverflow。你是我唯一的希望......

2 个答案:

答案 0 :(得分:3)

var paintings = [
    { "_id" : ObjectId("31c75"), "data" : "0,0,0,0" },
    { "_id" : ObjectId("deadb"), "data" : "1,3,0,255" }
]; 

绘画应该在array

 app.controller('PaintingCtrl', [
        '$scope',
        function($scope) {
            $scope.bindCanvas(canvasId) {
                var grid = new Grid(document.getElementById(canvasId));
                // Have fun with grid
            }
            //paintings should be on scope for ng-repeat to find it.
            // If ng-repeat does not find paintings on scope then it will create a new empty paintings object on scope
            $scope.paintings = [ 
              { _id : "31c75", data : "0,0,0,0" },
              { _id : "deadb", data : "1,3,0,255" }
             ];

        }
    ]);

<强>更新

我创造了2个掠夺者。

首先,plunker只使用canvas staticwidth创建height个元素。创建的canvas元素数量取决于painting.json文件中的绘画数量。

其次,plunker更进一步,使用canvas dynamicwidth创建height元素。创建的canvas元素数量取决于painting.json文件中的绘画数量。此处widthheight基于data文件中的paintings.json属性。

希望这有帮助。

答案 1 :(得分:0)

以下代码也适用于同一页面上的重复图表。

<div ng-repeat="a in abc">
    <canvas id="pieChart{{a}}" ng-bind = "bindCanvas(a)" ></canvas>
<div>

在JS文件中添加以下代码

$scope.abc = [1,2,3];

$scope.bindCanvas = function(i) {
    var ctx = document.getElementById("pieChart"+i);
    new Chart(ctx,{
        type: 'pie',
        data: {
            labels: ["Tele-conference", "Projector", "Laptop", "Desktop", "Coffee-machine"],
            datasets: [{
                label: "Population (millions)",
                backgroundColor: ["red", "green","blue","violet","yellow"],
                data: [200,100,300,400,150]
            }]
        },
    });
}