javascript - 如何在为每个项目呈现图表之前等待所有项目在 ng-repeat 中加载

标签 javascript angularjs chart.js

我正在使用 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 服务中提取的,因此它们需要几秒钟的时间才能出现在页面上,因此该元素在页面上实际可用 chart.js 来使用。

我试过使用 angular.element(document).ready() 无济于事。有没有其他方法可以强制 Controller 等到所有项目都先出现,然后再呈现图表?

最佳答案

您可以从您的 Controller 中放置一个$watch。在 $http.get().then() 完成中为 $scope 上的项目命名为 yourItems,请考虑以下示例

.controller('ScoringPolarCtrl', ['$scope', function($scope) {
    $scope.$watch('yourItems', function(newVal, oldVal) {
        if(newVal !== oldVal) {
            // render charts
        }
    });
}]);

您还可以在 Controller 上定义一个 $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
}

关于javascript - 如何在为每个项目呈现图表之前等待所有项目在 ng-repeat 中加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29826182/

相关文章:

javascript - ChartJs 3.x : ResizeObserver is not a constructor

javascript - 如何始终在 IE 中打开新窗口并使用新 session

javascript - 从数据库获取数据到angular js

javascript - 422(使用ajax提交表单时出现不可处理的实体错误

javascript - 如果在 angular.js 中数据字段为空,如何在 View 中显示默认值?

AngularJs $http 获取请求 - 如何显示进度条?

javascript - Chart.js 是否可以在单击图表上的点时触发 javascript?

javascript - Chart.js 错误 : TypeError: t is undefined

javascript - 悬停和 javascript 事件问题

javascript - jQuery 每个循环总是返回最后一个值