【发布时间】:2016-03-10 01:17:59
【问题描述】:
我正在尝试同时使用 d3 和 angular。我已经设置了以下 d3 模块:
angular.module('DTBS.d3', [])
.factory('d3Service', ['$document', '$q', '$rootScope',
function($document, $q, $rootScope) {
var d = $q.defer();
function onScriptLoad() {
// Load client in the browser
$rootScope.$apply(function() { d.resolve(window.d3); });
}
// Create a script tag with d3 as the source
// and call our onScriptLoad callback when it
// has been loaded
var scriptTag = $document[0].createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
scriptTag.src = 'http://d3js.org/d3.v3.min.js';
scriptTag.onreadystatechange = function () {
if (this.readyState == 'complete') onScriptLoad();
}
scriptTag.onload = onScriptLoad;
var s = $document[0].getElementsByTagName('body')[0];
s.appendChild(scriptTag);
return {
d3: function() { return d.promise; }
};
}]);
angular.module('DTBS.directives', [])
.directive('d3Bars', ['d3Service', function (d3Service) {
return {
restrict: 'EA',
scope: {},
link: function(scope, element, attrs) {
d3Service.d3().then(function(d3) {
// d3 code goes here
var svg = d3.select(element[0])
.append("svg")
.style('width', '100%');
scope.render = function (data) {
// remove all previous items before render
svg.selectAll('*').remove();
// If we don't pass any data, return out of the element
if (!data) return;
svg.selectAll('rect')
.data(data).enter()
.append('rect')
.attr('height', 50)
.attr('width', 50)
.style('background-color', red)
};
// set up watch to see if button clicked; add rectangle with render func
scope.$watch('data', function(newVals, oldVals) {
console.log("hey")
return scope.render(newVals);
}, true);
});
}};
}]);
在我的代码的主要部分,我有一个名为“DTBS.test”的模块。这个模块有一个表控制器,它有一个叫做“保存”的功能。我希望我的 d3 指令监视这个保存函数被调用,当它被调用时,应该调用渲染函数来向 svg 添加一个矩形。
angular.module('DTBS.test', [])
.controller('TableController', ['$scope', function ($scope) {
var secondsToWaitBeforeSave = 3;
$scope.table = {};
//Table save function that clears form and pushes up to the parent
$scope.save = function () {
$scope.id++;
$scope.table.id = $scope.id;
$scope.table.attrs = [];
$scope.addTable($scope.table);
$scope.table = {};
};
}])
目前它正在监视不存在的“数据”更改 - 我的问题是它应该监视什么以及如何将测试模块控制器中的事件链接到 d3 模块指令中的监视设置?
【问题讨论】:
标签: javascript angularjs d3.js svg