2015-06-06 45 views
1

最近我写了一个D3项目,所以我需要一个动态矩形。我使用Angular创建了一个动态可视化。我有两个input类型rang,第一个会改变矩形的“宽度”,第二个会改变“高度”。但是我不知道如何使用角度来绘制动态矩形。 这是我的代码:用Angular指令构建动态矩形

<div ng-app="myApp"> 
    <rect-designer/> 
    <div> 
    <input type="range" ng-model="rectWidth" min="0" max="400" value="0"/> 
    <input type="range" ng-model="rectHeight" min="0" max="700" value="0"/> 
    </div> 
</div> 

这里是我的JavaScript代码:

var App = angular.module('myApp', []); 
App.directive('rectDesigner', function() { 
    function link(scope, el, attr) { 

var svgwidth=1000, svgheight=600; 
var svgContainer = d3.select(el[0]).append('svg').attr('id','svgcontainer') 
     .attr({ width: svgwidth, height: svgheight }); 

scope.$watchGroup(['rectWidth','rectHeight'], function() { 

     svgContainer.append("rect").attr("id", "Rect") 
     .attr({ width: rectWidth, height: rectHeigh }) 
     .attr('transform', 'translate(' + width/2 + ',' + height/2 + ')') 


    },true); 
    }return { 

    link: link, 
    scope: { 
     rectHeigh: '=', 
     rectWidth: '=', 

    }, 
    restrict: 'E' 
}; 
}); 

我不知道是否有什么办法,使svgWidthsvgheight动态的,我用这个代码,但结果是undefined

scope.$watch(function(){ 
      svgWidth = el.clientWidth; 
      svgHeight = el.clientHeight; 
    }); 

回答

2

您在这里缺少一些基本知识:

  1. 你没有一个控制器。
  2. 你正在看的变量不是你的指令的一部分,但他们应该是缺失控制器的一部分。
  3. 由于这些变量不是指令的一部分,因此不需要将它们返回到它的范围(再次,它们将位于控制器中)。
  4. $scope.watchGroup有一个回调函数newValues。这是变化后的变量。
  5. 你想追加rect的SVG,然后操纵它的宽度/高度。每当宽度/高度改变时,您都不想重新添加它。

所以把所有这些组合起来:

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

var Ctrl = App.controller('myCtrl', ['$scope', function($scope) { 

    // I always like to give them defaults in code 
    $scope.rectWidth = 50; 
    $scope.rectHeight = 50; 

}]); 

Ctrl.directive('rectDesigner', function() { 

    function link(scope, el, attr) { 

    var svgwidth = 500, 
     svgheight = 600; 

    var svgContainer = d3.select(el[0]) 
     .append('svg') 
     .attr('id', 'svgcontainer') 
     .attr({ 
     width: svgwidth, 
     height: svgheight 
     }); 
    // only append one rect 
    var rect = svgContainer 
     .append("rect") 
     .attr("id", "Rect") 
     .attr('transform', 'translate(' + svgwidth/2 + ',' + svgheight/2 + ')'); 

    scope.$watchGroup(['rectWidth', 'rectHeight'], function(newValues) { 

     var width = newValues[0]; 
     var height = newValues[1]; 

     // now change it's width and height 
     rect.attr({ 
     width: width, 
     height: height 
     }); 

    }, true); 
    } 
    return { 
    link: link, 
    }; 
}); 

here

+0

谢谢亲爱的马克,那真是太棒了。 – Gabriel