[英]How do I get data from a json file into an angularjs directive function?
我正在尝试使用Angularjs指令来绘制画布元素。 我想从json文件中提取要绘制的画布元素数和该元素的属性。
// 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的属性在第一个画布list元素中,第二个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)",
},
]
我想将其放入这样的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
您可以将列表数据作为值应用到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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.