【发布时间】:2014-06-26 00:47:10
【问题描述】:
我有一个控制器(下面的代码),它链接到 d3-cloud 指令并且运行良好。数据被添加到控制器中并传递给指令。
myApp.controller('DownloadsCloudCtrl', ['$scope',
'$rootScope',
'requestService',
'$cookieStore',
function($scope, $rootScope, requestService, $cookieStore){
$scope.d3Data = [
{
'kword': 'a',
'count': 141658,
},{
'kword': 'b',
'count': 105465,
}
];
}]);
现在我正在尝试通过将控制器切换到以下代码来从 JSON 请求服务中提取数据。当我在$scope.d3Data = data 行下方的控制器中执行console.log 时,一切似乎都正常工作(返回了正确的数据)。
但是,当尝试将控制器链接到指令时,由于某种原因,指令正在获取未定义/空数据集。
我想知道问题是否在于代码执行的顺序。也许控制器试图在 JSON 服务完成之前将数据传递给指令,从而导致没有绘制图形。会不会发生这种情况,如果发生了,我该如何解决?
myApp.controller('DownloadsCloudCtrl', ['$scope',
'$rootScope',
'requestService',
'$cookieStore',
function($scope, $rootScope, requestService, $cookieStore){
$rootScope.$on('updateDashboard', function(event, month, year) {
updateDashboard(month, year);
});
var updateDashboard = function(month, year) {
requestService.getP2PKeywordData(month, year).then(function(data) {
$scope.d3Data = data;
});
};
updateDashboard($cookieStore.get('month'), $cookieStore.get('year'));
}]);
编辑:指令代码:
myApp.directive('d3Cloud', ['$window',
'd3Service',
'd3Cloud',
function($window,
d3Service,
d3Cloud) {
return {
// Restrict usage to element/attribute
restrict: 'EA',
// Manage scope properties
scope: {
// Bi-directional data binding
data: '=',
// Bind to DOM attribute
label: '@'
},
// Link to DOM
link: function(scope, element, attrs) {
// Load d3 service
d3Service.d3().then(function(d3) {
// Re-render on window resize
window.onresize = function() {
scope.$apply();
};
// Call render function on window resize
scope.$watch(function() {
return angular.element($window)[0].innerWidth;
}, function() {
scope.render(scope.data);
});
// Render d3 chart
scope.render = function(data) {
// d3 specific appends... not important
HTML 代码:(足够简单)
<div class="col-md-6">
<div class="module">
<div class="inner-module" ng-controller="DownloadsCloudCtrl">
<div class="module-graph">
<d3-cloud data="d3Data"></d3-cloud>
</div>
</div>
</div>
</div>
【问题讨论】:
-
您能否显示指令的代码和/或将数据(如果使用隔离范围)传递给指令的模板?
标签: javascript json angularjs d3.js