是否可以使用范围变量在html中访问数组?

时间:2017-01-10 17:40:09

标签: javascript angularjs

我想在我的模板文件中使用Json数组,但要访问数组的某些元素,我需要使用范围变量。我可以在控制器中执行类似的操作,但我需要在html文件中执行此操作。

我的阵列的一部分如下所示:

{
fitbit: {
    selected: true,
    user_id: "10537",
    today: [
        {
            date: "Tue, 10 Jan 2017",
            distance: 0,
            steps: 0,
            calories: "0"
        }
    ],
    week: {
        distance: [
            ["0","0","0","0","0"]
        ],
        labels: ["Wed 4th","Thu 5th","Fri 6th","Sat 7th","Sun 8th"],
        steps: [
            ["0","0","0","0","0"]
        ]
    }
},
jawbone: { ... }
}

我有一个范围变量$scope.currentDevice,它将根据用户选择的选项进行更改,如fitbit,jawbone等。 在控制器中,我可以控制使用哪些数据 $scope.wearables[currentDevice]['week']['distance']以便使用变量currentDevice获取正确的数据。

我需要访问模板html文件中的wearables[currentDevice]['week']['distance']但不使用ng-repeat,我需要使用范围变量currentDevice来决定要显示哪些数据。

每当我在html文件中尝试{{wearables[currentDevice]['week']['distance']}}时,它都会显示任何内容,但如果我尝试{{wearables['fitbit']['week']['distance']}}则会显示该值。

是否可以通过这种方式显示数组数据?如果可以,我该怎么做?

我想要显示的数组数据需要显示在图表数据更改的下图中

<canvas id="bar" class="chart chart-bar" chart-data="wearables[currentDevice]['week']['distance']" chart-labels="labels" chart-series="series" chart-options="options" ></canvas>

如果我将其更改为

<canvas id="bar" class="chart chart-bar" chart-data="wearables['fitbit']['week']['distance']" chart-labels="labels" chart-series="series" chart-options="options" ></canvas> 

一切正常

2 个答案:

答案 0 :(得分:0)

为了在图表中显示正确的数据,我使用了一个函数。而不是尝试使用wearables[currentDevice]['week']['distance']显示数据我使用getDistance(currentDevice)来返回正确的数据

图表代码变为:

<canvas id="bar" class="chart chart-bar" chart-data="getDistance(currentDevice)" chart-labels="labels" chart-series="series" chart-options="options" ></canvas>

并且在控制器中,getDistance(device)方法是数据根据$ scope.currentDevice的变化而变化的地方:

$scope.getDistance = function(device) {
    console.log('current device', device );
    return $scope.wearables[device]['week']['distance'];
}

答案 1 :(得分:-2)

根据实际推动图表的内容,chart-data属性可能无法正确评估。尝试将chart-data更改为ng-attr-chart-data,看看是否有效:

<canvas id="bar" class="chart chart-bar" ng-attr-chart-data="wearables[currentDevice]['week']['distance']" chart-labels="labels" chart-series="series" chart-options="options" ></canvas>

有关ngAttr的信息:https://docs.angularjs.org/guide/interpolation