【问题标题】:Render Chart on second template by clicking icon on the first template通过单击第一个模板上的图标在第二个模板上渲染图表
【发布时间】:2017-02-24 23:52:51
【问题描述】:

我一直在开发一个使用图表 JS 的移动应用程序。我被困在一个需要通过单击图标来绘制图表的地方。

问题是,图标在template1.html,图表应该在template2.html绘制。我正在使用 angularJS。因此,每个图表都有其控制器。

因此,图表的所有代码都在 template2Controller 中。问题来了,如何通过单击 template1.html 处的图标在 template2.html 处绘制图表。

template1.html

<button class="" ng-click="daily()"> </button>

template2.html

<div id="dailyTab" class="chart" > <canvas id="dailyChart" ></canvas> </div>

template2Controller

$scope.daily = function() {
    $http.get('jsonAPIURL'
).success(function(response) {

       var dailyCoffee = [];
      angular.forEach(response, function(value, key) {
        dailyCoffee.push(value.Currency);
      });

      var daily = {
        labels: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
        datasets: [{
      backgroundColor: "rgb(3,191,179)",
          data: dailyCoffee
        }]
      };
      var ctx = document.getElementById('dailyChart').getContext('2d');

      var chartDaily = new Chart(ctx, {
        type: 'bar',
        data: daily,
         options: {
            responsive: true
              }
      });

    });
  };

【问题讨论】:

    标签: javascript html angularjs ionic-framework chart.js


    【解决方案1】:

    控制器之间有什么关系吗?他们是父母/孩子吗?如果是这样,您可以使用 AngularJs 事件 ($emit, $broadcast)。

    如果没有,您可能希望使用一个共同的父祖先,(如果没有,您可以使用 rootScope`)在单击时触发事件,并使用 $scope.$on 来监听该事件并绘制图表。类似的东西

    模板 1 HTML

    ng-click="drawChart()"
    

    模板 1 控制器

    $scope.drawChart = function(){
          // $root scope must be injected in the controller. Use the name you prefer
          $rootScope.$broadcast('draw-custom-chart');
    };
    

    Template2Controller

    $scope.$on('draw-custom-chart', function($event){
        $event.stopPropagation();
        $scope.daily();
    });
    

    我相信,一个更好的方法是将daily() 函数移到服务中,并注入到 Template1Controller 并从那里调用它。如果你在 Template2Controller 中也需要它,你也可以在那里注入它。

    【讨论】:

    • 但是它没有在template2.html上渲染图表?我在 template2.html 中的 下发送了图表 ID。
    • 带有事件的代码应该在 template2.html 中呈现。如果不是,我相信您的渲染代码可能有问题,但是如果您使用调试器,您会看到正在调用控制器 2 中的代码
    • 谢谢!你解决了我的问题! :)
    猜你喜欢
    • 1970-01-01
    • 2011-10-17
    • 2017-08-06
    • 2017-02-08
    • 2020-02-13
    • 2022-01-24
    • 2016-07-12
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多