如何将json文件中的数据导入angularjs指令函数?

时间:2016-08-03 18:20:30

标签: javascript angularjs json canvas angularjs-directive

我正在尝试使用Angularjs指令来绘制画布元素。我想从json文件中提取要获取要绘制的canvas元素的数量和元素的属性。

// Define the `myApp` module
var myApp = angular.module('myApp', []);

// Define the `ListController` controller on the `myApp` module
myApp.controller('ListController', function ListController($http, $scope) {
    $http.get('list.data.json').then(function (response) {
        $scope.lists = response.data;
    });
}).directive("appListDraw", function appListDraw() {
    return {
        restrict: 'A',
        link: function (scope, element){
            var ctx = element[0].getContext('2d');
            ctx.fillStyle = "rgb(200,0,0)"; //I want to insert json data here (list.fill1)
            ctx.fillRect(10, 10, 50, 50);

            ctx.fillStyle = "rgba(0, 0, 200, 0.5)"; //I want to insert json data here (list.fill2)
            ctx.fillRect(30, 30, 50, 50);
            ctx.stroke();
        }

    }

});

目标是我将有list.id 1的属性将在第一个canvas列表元素和list.id 2的属性在第二个

list.data.json看起来像这样:

[
    {
        "id": 1,
        "fill1": "rgb(200,0,0)",
        "fill2": "rgba(0,0,200,0.5)",
    },
    {
        "id": 2,
        "fill1": "rgb(40,0,0)",
        "fill2": "rgba(0,0,200,0.5)",
    },
]

我想把它放到像这样的画布元素中:

<ul>
  <li ng-repeat="list in lists">
    <canvas name='canvas' width="800" height="100" app-list-draw></canvas>
  </li>
</ul>

有没有办法可以做到这一点?

我添加了 Plunker: http://plnkr.co/edit/gbg6CWVNn1HziSYSTtPP?p=preview

1 个答案:

答案 0 :(得分:1)

您可以将列表数据作为值应用于canvas元素中的指令名称属性,并从指令范围访问数据:

https://jsfiddle.net/kucaexp4/

HTML

<ul>
  <li ng-repeat="list in lists">
    <canvas name='canvas' width="800" height="100" app-list-draw="list"></canvas>
  </li>
</ul>

directive("appListDraw", function appListDraw() {
    return {
        restrict: 'A',
        scope: {
            list: '=appListDraw'
        },
        link: function (scope, element){
           var ctx = element[0].getContext('2d');
           ctx.fillStyle = scope.list.fill1; //I want to insert json data here (list.fill1)//
           ctx.fillRect(10, 10, 50, 50);

           ctx.fillStyle = scope.list.fill2; //I want to insert json data here (list.fill2)
           ctx.fillRect(30, 30, 50, 50);
           ctx.stroke();
       }
}