Ryan Ryan - 3 months ago 10
Javascript Question

How do I get data from a json file into an angularjs directive function?

I am trying to use an Angularjs directive to draw canvas elements. I want to pull from a json file to get both the number of canvas elements to draw and properties for the element.

// 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();
}

}

});


With the goal being I'll have list.id 1's properties will be in the first canvas list element and list.id 2's properties on the second

list.data.json looks like this:

[
{
"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)",
},
]


And I want to put it into a canvas element like this:

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


Is there a way I can do this?

I've added a Plunker: http://plnkr.co/edit/gbg6CWVNn1HziSYSTtPP?p=preview

Rob Rob
Answer

You can apply the list data as a value to the directive name attribute in the canvas element and access the data from the directive scope:

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>

Angular

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();
       }
}
Comments