AngularJS 传递给指令重 JSON 文件
-
21-12-2019 - |
题
好吧,我想我找到了图表未显示的问题,问题可能是我正在从 RESTful 服务器加载大量 JSON 对象并将其传递给我生成图表的指令,但 json 尚未完全下载。
JSON 文件几乎有 1mb,我是这样获取的:
在控制器中:
dataArchive.get().then(function(result){
$scope.getData = result;
});
和 HTML:
<divng-controller="archiveCtrl">
<data-graph get-archive-data="getData"></data-graph>
</div>
并在指令中:
var chart = function(data){
var createchart = new AmCharts.makeChart("chartdiv", {
//
});
}
var linker = function(scope, element, attrs){
scope.$watch('data', function(){
chart(scope.data);
});
}
directives.directive('dataGraph', function(){
return {
restrict: 'E',
replace: false,
scope: {
data: '=getArchiveData'
},
template: '<div id="chartdiv"></div>',
link: linker
};
});
可能正因为如此,指令模板将被创建为空,并且不会生成图表。我该如何解决这个问题?
解决方案
您正在正确使用 $watch
这应该会重新触发图表功能,但我建议您尝试其他一些方法来看看哪个有帮助。
首先,监视功能将在初始指令链接时触发,即使 data
还不存在——它只会返回 undefined
, ,所以第一次它将调用图表函数 undefined
, ,因此,我想,渲染一个空图表。然后,当数据下载完成后,就会触发 $watch
再次,但如果多次调用,您的图表函数可能将无法工作..?怎么样进行以下检查:
scope.$watch('data', function(){
if (!scope.data) return
chart(scope.data);
});
当我需要等待某些变量的解析时,另一种对我有用的方法是使用 $observe
, ,并且不将变量添加到指令的范围中:
<data-graph get-archive-data="{{ getData }}"></data-graph>
var linker = function(scope, element, attrs){
attrs.$observe('getArchiveData', function(data){
if (!data) return;
chart(data);
});
}
directives.directive('dataGraph', function(){
return {
restrict: 'E',
replace: false,
// Remove below
//scope: {
// data: '=getArchiveData'
//},
template: '<div id="chartdiv"></div>',
link: linker
};
});
不隶属于 StackOverflow