2014-09-01 146 views
0

我想根据数据制作不同颜色矩形的xy图。 X是天,Y是一天中的小时。它是一个活动图。如何在自定义指令中添加SVG angularjs标签?

的index.html

<html> 
<body> 
    <script src="js/angular.js"></script> 
    <script> 
     var app = angular.module("app",[]); 
     app.controller("controller",function($scope){ 

     }); 
     app.directive("graph",function(){ 
      return { 
       controller:function($scope){ 
        $scope.val=50; 
       }, 
       templateUrl:"test.html", 
       scope:{ 
        code:"=" 
       }, 
       restrict:"E" 
      } 
     }); 
    </script> 
    <div ng-app="app" ng-controller="controller"> 
     <graph></graph> 
    </div> 
</body> 
</html> 

的test.html

<svg> 
    <rect x="0" x="0" ng-attr-width="{{val}}" ngheight="50"></rect> 
</svg> 

回答

1

这里是将与SVG代替的简单指令的一个例子:

var app = angular.module('app', []); 

app.directive('graph', function(){ 
    return { 
    replace: true, 
    restrict: 'E', 
    scope: { 
     data: '=' 
    }, 
    template: '<svg><g><rect ng-repeat="item in data" x="{{item.x}}" y="{{item.y}}" width="{{item.width}}" height="{{item.height}}"></rect></g></svg>' 
    }; 
}); 

将用于如在following plunker中那样。但是,这种

注:

  1. 当DOM被解析,因为{{item.x}}是直到表达是由角评估x属性的有效值你会得到一堆错误。您可以通过定义可将评估值应用于DOM的自定义graph-xgraph-ygraph-*指令来克服此问题。更多细节可以在这个issue找到。

  2. 如果你想做更复杂的事情,我建议你看看一个伟大的图书馆D3.js这就像jQuery svg中的数据可视化。

+0

ty @miensol您的回复。我尝试从头开始,它的工作!文档在angularjs.org上。 ng-attr-x工作! [截图](http://pic.twitter.com/Un2x7bg6rq) – Montu 2014-09-03 07:52:47

相关问题