[英]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.