【问题标题】:How do I get data from a json file into an angularjs directive function?如何从 json 文件中获取数据到 angularjs 指令函数中?
【发布时间】:2016-08-03 18:20:29
【问题描述】:

我正在尝试使用 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.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

【问题讨论】:

    标签: javascript angularjs json canvas angularjs-directive


    【解决方案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();
           }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 2017-09-07
      • 2016-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多