2016-08-03 14 views
0

Angularjsディレクティブを使用してキャンバス要素を描画しようとしています。私はjsonファイルから、描画するキャンバス要素の数と要素のプロパティの両方を取得する必要があります。目標は、私は1のプロパティは、最初のキャンバスのリスト要素になりますlist.idと第二jsonファイルからangularjsディレクティブ関数にデータを取得するにはどうすればよいですか?

list.data.jsonに2のプロパティをlist.idていますされた状態で

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

    } 

}); 

は次のようになります。

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

そして、私はこのようなcanvas要素に入れたい:

<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

あなたはcanvas要素でディレクティブname属性の値として、リストデータを適用し、指示範囲からデータにアクセスすることができます。

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(); 
     } 
} 
関連する問題