简体   繁体   中英

How can I use an angular component more then once?

I am using angular component to load dynamic charts into my widget:

Here is a example of my component:

angular.module("generalApp").component("chartPie", {
template: "<div class=Pie></div>",
bindings: {
    data: "=",
},
controller: function () {
    $('.Pie').highcharts({
        title: {
            text: 'Pie point CSS'
        },

        xAxis: {
            categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        },

        series: [{
            type: 'pie',
            allowPointSelect: true,
            keys: ['name', 'y', 'selected', 'sliced'],
            data: [
                ['Apples', 29.9, false],
                ['Pears', 71.5, false],
                ['Oranges', 106.4, false],
                ['Plums', 129.2, false],
                ['Bananas', 144.0, false],
                ['Peaches', 176.0, false],
                ['Prunes', 135.6, true, true],
                ['Avocados', 148.5, false]
            ],
            showInLegend: true
        }]
    })
}
});

This renders a pie chart on the widget. This is how my json object looks likes:

{  
     "Id":0,
     "description":"Test1",
     "datasource":"Data",
     "charttype":"Pie",
     "x":0,
     "y":0,
     "width":3,
     "height":2
},

This is going good. But when I want to make another widget with a pie chart it doesn't render the pie chart anymore.

Array with two widgets objects:

[
    {  
        "Id":0,
        "description":"Test1",
        "datasource":"Data",
        "charttype":"Pie",
        "x":0,
        "y":0,
        "width":3,
        "height":2
    },
    {  
        "Id":0,
        "description":"Test2",
        "datasource":"Data",
        "charttype":"Pie",
        "x":3,
        "y":0,
        "width":3,
        "height":2
    }
]

On index.html

<div ng-switch-when="Pie">
   <chart-pie></chart-pie>
 </div>

The widgets:

渲染

How can I use the component more then once?

Kind regards

The $('.Pie') selector is too general and will pick up every element with that class in the whole document.

Inject $element into the controller and only search for .Pie within your component element:

angular.module("generalApp").component("chartPie", {
    template: "<div class=Pie></div>",
    bindings: {
        data: "=",
    },
    controller: function ($element) {
        $element.find('.Pie').highcharts({
            // ...
        })
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM