在同一视图中使用相同的指令并绑定不同的数据 [英] Use same directive in same view and bind different data
问题描述
我创建了一个自定义指令,用于显示使用 Highcharts 库制作的图表.
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.
指令
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
});
}
控制器
vm.title = "My Chart";
html-template
<date-chart></date-chart>
<date-chart></date-chart>
推荐答案
首先你需要告诉指令数据将被传递
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
});
}
因此,如果图表的数据位于 $scope.someData1
和 $scope.someData2
,您可以像这样传递它:
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>
这篇关于在同一视图中使用相同的指令并绑定不同的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!