[英]Build dynamic rectangle with Angular directive
最近,我用D3编写了一个项目,因此我需要一个动态矩形。 我用角创建动态visualization.I具有两个input
类型rang
,第一个将改变矩形的“宽度”和第二将改变“height'.However我不知道如何使用角度来绘制动态矩形。 这是我的代码:
<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'
};
});
我不知道是否有任何方法可以使svgWidth
和svgheight
动态化,我使用了这段代码,但是结果是undefined
。
scope.$watch(function(){
svgWidth = el.clientWidth;
svgHeight = el.clientHeight;
});
您在这里缺少一些基础知识:
$scope.watchGroup
有一个具有newValues
函数的回调。 这是更改后的变量所在的位置。 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,
};
});
这里的例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.