将两个javascripts合并为一个foreach

时间:2017-05-22 15:46:03

标签: javascript php laravel blade

我的laravel刀片视图中有javascript。我想知道我是否可以将这两个脚本合并为一个。 每个引导程序选项卡中的脚本显示图。

首先写剧本:

var chart1 = AmCharts.makeChart( "chart_visits", {
        "dataProvider": [
            @foreach($results as $result)
                {
                    "date": "{{ date('Y-m-d', strtotime($result->time)) }}",
                    "value": '{{ $result->stats->visits }}'
                },
            @endforeach
        ]
    } );

脚本第二:

var chart1 = AmCharts.makeChart( "chart_visits", {
        "dataProvider": [
            @foreach($results as $result)
                {
                    "date": "{{ date('Y-m-d', strtotime($result->time)) }}",
                    "value": '{{ $result->stats->bounceRate }}'
                },
            @endforeach
        ]
    } );

这是我的观点:

<ul class="nav nav-tabs">
    <li>
        <a href="#bounce" data-toggle="tab"> Bounce rate </a>
    </li>
    <li class="active">
        <a href="#visits" data-toggle="tab"> Visits </a>
    </li>
</ul>

<div class="tab-content">
    <div class="tab-pane active" id="visits">
        <div class="chartdiv" id="chart_visits"></div>
    </div>

    <div class="tab-pane" id="bounce">
        <div class="chartdiv" id="chart_bounce"></div>
    </div>
</div>

2 个答案:

答案 0 :(得分:0)

如果我理解你正确的方法,那么你想要做的就是简单地从对象集合创建普通数组并迭代它。类似的东西:

var chart1 = AmCharts.makeChart( "chart_visits", {
    "dataProvider": [
        @foreach($results as $result)
        {
            "date": "{{ date('Y-m-d', strtotime($result['date'])) }}",
            "value": "{{ $result['value'] }}"
        },
        @endforeach
    ]
} );

答案 1 :(得分:0)

正确的答案是jquery函数extend

两者相同的脚本,我不想干:

var config = {
            "type": "serial",
            "theme": "light",
            "marginRight": 40,
            "marginTop": 60,
            "marginLeft": 40,
            "autoMarginOffset": 0,
            "dataDateFormat": "YYYY-MM-DD",
        };

第一个将在两个脚本中扩展重复值的脚本:

AmCharts.makeChart( "chart_leads", jQuery.extend({}, config, {
            "dataProvider": [
                    @foreach($results as $result)
                {
                    "date": "{{ date('Y-m-d', strtotime($result->time)) }}",
                    "value": '{{ $result->stats->leads }}'
                },
                @endforeach
            ]
        } ));

第二个脚本将扩展两个脚本中的重复值:

AmCharts.makeChart( "chart_visits", jQuery.extend({}, config, {
            "dataProvider": [
                    @foreach($results as $result)
                {
                    "date": "{{ date('Y-m-d', strtotime($result->time)) }}",
                    "value": '{{ $result->stats->visits }}'
                },
                @endforeach
            ]
        } ));