Use same directive in same view and bind different data

谁说胖子不能爱 提交于 2019-12-24 08:24:14

问题


I have created a custom directive for displaying a charts made with the Highcharts library.

Now I want to build upon this directive and create multiple charts in the same view.

This is not possible with the current code I have, as you can see below.

How can I organize my code so that it's possible to bind different data to it in the same view?

Below is some example code to illustrate the problem.

Directive

 function dateChart() {
  return {
    restrict: 'AE',
    scope: {
      title: '@'
    },
    template: '<div id="chart"></div>',
    link: function(scope, element, attrs) {
      var chart;

      function createChart() {
        chart = new Highcharts.Chart({
          chart: {
          title: scope.title
        });
      }

Controller

vm.title = "My Chart";

html-template

  <date-chart></date-chart>

  <date-chart></date-chart>

回答1:


First you need to tell the directive that data will be passed along

 function dateChart() {
  return {
    restrict: 'AE',
    scope: {
      title: '@'
      chartData: '='
    },
    template: '<div id="chart"></div>',
    link: function(scope, element, attrs) {
      var chart;

      function createChart() {
        chart = new Highcharts.Chart({
          chart: {
          title: scope.title
        });
      }

So if the data for your charts is at $scope.someData1 and $scope.someData2 you can pass it along like this:

<date-chart chart-data="someData1"></date-chart>

<date-chart chart-data="someData2"></date-chart>


来源:https://stackoverflow.com/questions/39991627/use-same-directive-in-same-view-and-bind-different-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!