使用svg和ng-repeat在大矩形内部制作多个小矩形

时间:2017-08-10 16:06:15

标签: angularjs svg angularjs-ng-repeat rectangles

我有这个代码,我需要在一个大矩形内显示多个小矩形,我需要多次完成整个过程。

这是我的数据:

"data": {
  "rect1": { 
     "a":[10,20],
     "b":[35,10] 
   },
   "rect2": {
     "y":[25,10],
     "z":[55,20] 
   }
}

这个数据应该分别在两个矩形rect1和rect2以及两个矩形内分别为a,b和y,z。每个小矩形都有起始位置x和该小矩形的宽度,例如a从x 10开始,宽度= 20。

<ul>
    <li ng-repeat="(rect,coords) in data">
    <svg>
    <rect x=1 y=1 width=1000 height=50 style="fill:grey;" />
    <span ng-repeat="coord in coords">
    <rect x={{coord[0]}} y=1 width={{coord[1]}} height=50 style="fill:blue;" />             


                 enter code here

但是这段代码没有用,因为我在两个标签之间添加了ng-repeat线。

image of what the final result should look like

我在powerpoint中制作了这张图片,所以忽略背景。

1 个答案:

答案 0 :(得分:1)

你非常接近。您无法在SVG中使用<span>。但其余大部分都是正确的。

最好使用ng-attr-x="{{value}}代替x="{{value}}。否则,SVG解析器将抛出错误,因为它不理解字符串"{{value}}"

这是一个有效的例子。

&#13;
&#13;
var app = angular.module('myApp', [])

app.controller("AppCtrl", ["$scope", function($scope) {
  
  $scope.data = {
    "rect1": { 
       "a":[10,20],
       "b":[35,10] 
     },
     "rect2": {
       "y":[25,10],
       "z":[55,20] 
     }
  };

}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">

  <ul ng-controller="AppCtrl">
    <li ng-repeat="(rectName, coords) in data">
      <svg id="{{rectName}}" width="100%" height="50">
        <rect x="1" y="1" width="1000" height="50"
              style="fill: lightgrey;" />
        <rect ng-repeat="(label, coord) in coords"
              ng-attr-x="{{coord[0]}}" y="1"
              ng-attr-width="{{coord[1]}}" height="50"
              style="fill: blue;" />
        <text ng-repeat="(label, coord) in coords"
              ng-attr-x="{{coord[0]}}" y="25"
              style="fill: white;">{{label}}</text>
      </svg>
    </li>
  </ul>

</div>
&#13;
&#13;
&#13;