如何在为每个项目呈现图表之前等待所有项目在 ng-repeat 中加载
How to wait for all items to load within ng-repeat before then rendering a chart for each item
我正在使用 ng-repeat
在页面上显示大量报告项目。每个项目都有大量数字,因此我们想为每个项目显示一个小图表。
我已经设置了一个指令来在每个项目中呈现图表并将数据传递给指令。然而,在渲染图表时,我依靠一个按钮来强制更新:
App.controller('ScoringPolarCtrl', ["$scope", function($scope){
$scope.forceUpdate = function () {
console.log("Attempting to render chart ID: " + itemId);
var ctx = document.getElementById(itemId).getContext("2d");
$scope.scoreChart = new Chart(ctx)
$scope.scoreChart.PolarArea($scope.scoreChartData,
$scope.itemScoreChartOptions);
};
}]);
这可行,但我想做的是在不依赖 forceUpdate()
函数的情况下以某种方式呈现图表。
这些项目都是使用 $http
从 Web 服务中提取的,因此它们需要几秒钟才能出现在页面上,因此该元素在 [=14] 页面上实际可用=] 使用。
我试过 angular.element(document).ready()
没用。有没有其他方法可以强制控制器等到所有项目都先出现,然后再呈现图表?
您可以从您的控制器中放置一个 $watch
。在 $http.get().then()
完成中为 $scope
上的项目命名 yourItems
,请考虑以下示例
.controller('ScoringPolarCtrl', ['$scope', function($scope) {
$scope.$watch('yourItems', function(newVal, oldVal) {
if(newVal !== oldVal) {
// render charts
}
});
}]);
您还可以在控制器上定义一个 $scope
函数,并在 $http
回调中调用 from 指令。如果您是否隔离 $scope
,这看起来可能会有所不同,但这是基本思想
// -- directive
$http.get('/foo').then(function(results) {
scope.renderCharts(results); // -- async complete
});
// -- controller
$scope.renderCharts = function(results) {
// render charts -- this is called once you receive your $http response
}
我正在使用 ng-repeat
在页面上显示大量报告项目。每个项目都有大量数字,因此我们想为每个项目显示一个小图表。
我已经设置了一个指令来在每个项目中呈现图表并将数据传递给指令。然而,在渲染图表时,我依靠一个按钮来强制更新:
App.controller('ScoringPolarCtrl', ["$scope", function($scope){
$scope.forceUpdate = function () {
console.log("Attempting to render chart ID: " + itemId);
var ctx = document.getElementById(itemId).getContext("2d");
$scope.scoreChart = new Chart(ctx)
$scope.scoreChart.PolarArea($scope.scoreChartData,
$scope.itemScoreChartOptions);
};
}]);
这可行,但我想做的是在不依赖 forceUpdate()
函数的情况下以某种方式呈现图表。
这些项目都是使用 $http
从 Web 服务中提取的,因此它们需要几秒钟才能出现在页面上,因此该元素在 [=14] 页面上实际可用=] 使用。
我试过 angular.element(document).ready()
没用。有没有其他方法可以强制控制器等到所有项目都先出现,然后再呈现图表?
您可以从您的控制器中放置一个 $watch
。在 $http.get().then()
完成中为 $scope
上的项目命名 yourItems
,请考虑以下示例
.controller('ScoringPolarCtrl', ['$scope', function($scope) {
$scope.$watch('yourItems', function(newVal, oldVal) {
if(newVal !== oldVal) {
// render charts
}
});
}]);
您还可以在控制器上定义一个 $scope
函数,并在 $http
回调中调用 from 指令。如果您是否隔离 $scope
,这看起来可能会有所不同,但这是基本思想
// -- directive
$http.get('/foo').then(function(results) {
scope.renderCharts(results); // -- async complete
});
// -- controller
$scope.renderCharts = function(results) {
// render charts -- this is called once you receive your $http response
}