我有下面的代码作为指令。我试图将scope从控制器传递到这个指令,并且它似乎正在正确地传递它(console.log(scope);工作正常)。但是,当我尝试访问scope.data属性时(它看起来应该返回console.log for scope中的一个数组),它将返回undefined。这是为什么,我怎么能解决这个问题?
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) {
// Create svg variable
var svg = d3.select(element[0])
.append('svg')
.style('width', '100%')
.append('g');
// 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() {
// Works fine!
console.log(scope);
// Returns undefined!
console.log(scope.data)
scope.render(scope.data);
});
...添加了
<div class="inner-module" ng-controller="DownloadsCloudCtrl">
<div class="module-graph">
<d3-cloud data="d3Data"></d3-cloud>
</div>
</div>重要编辑:
问题变得越来越奇怪了。我刚刚刷新了页面,它完美地抓取了数据。再次刷新并再次接收undefined。我将尝试将变量名从数据更改为其他内容。
编辑2:
尝试更改变量名,它似乎不识别除data以外的任何参数.奇怪..。
发布于 2014-06-26 16:59:44
问题:
该指令是在http服务完成数据加载之前加载的。
解决方案:
添加一个ng-if条件,以确保数据在启动指令之前已经加载。
标记:
<div class="module-graph" ng-if="dataLoaded">
<d3-cloud data="d3Data"></d3-cloud>
</div>控制器内的:
requestService.getP2PKeywordData(month, year).then(function(data) {
$scope.d3Data = data.data;
$scope.dataLoaded = true;
});https://stackoverflow.com/questions/24435484
复制相似问题