我想一起使用d3和角度。我建立了以下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模塊的指令?
的任何位置添加'scope.data = [// data here]',這正是我正在尋找並完美工作的地方!不能太感謝你了,太棒了 –