我的循环只显示我视图中的最后一个数据值 - firebase

时间:2017-09-12 04:49:37

标签: html angularjs firebase firebase-realtime-database

我试图显示我使用angular.foreach从firebase数据库中检索的所有设备列表但是当我尝试在我的视图中显示检索到的值时,它只显示最后一个值。需要帮助!

我的JS

/*global angular*/
var app = angular.module('sdt', ['ngRoute', 'firebase']);

app.config(['$routeProvider', function ($routeProvider) {
    'use strict';
    $routeProvider.when('/sdt', {
        templateUrl: 'searchdowntime/sdt.html',
        controller: 'sdtCtrl'
    });
}]);

app.controller('sdtCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function ($scope, $firebaseObject, $firebaseArray) {
    'use strict';

    var ref = firebase.database().ref();
        var data = ref.child("data");
        var list = $firebaseArray(data);

        list.$loaded().then(function(data) {
            $scope.data = data;
            angular.forEach ($scope.data , function (d) {
                angular.forEach (d.equipments, function (e) {
                    $scope.allEquipments = e;
                    console.log($scope.allEquipments);
                })
            });
            console.log($scope.data);
        }).catch(function(error) {
            $scope.error = error;
        });




}]);

我的HTML

<div class="table-responsive">
  <table class="table table-striped table-hover">
     <tr>
        <th id="system">System</th>
        <th id="equipment">Equipment</th>
        <th id="date">Date</th>
        <th id="type">Type</th>
     </tr>
     <tr data-ng-repeat="d in allEquipments">
        <td headers = "system">System</td>
        <td headers = "equipment" >{{d}}</td>
        <td headers = "date">date</td>
        <td headers = "type">Standby</td>
     </tr>
  </table>

控制台日志:

console log

视图:

view

1 个答案:

答案 0 :(得分:1)

那是因为你总是为每次迭代改变$scope.allEquipments的值。你需要将它推入一个数组。

app.controller('sdtCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function ($scope, $firebaseObject, $firebaseArray) {
    'use strict';

    // Add this line
    $scope.allEquipments = [];
    var ref = firebase.database().ref();
        var data = ref.child("data");
        var list = $firebaseArray(data);

        list.$loaded().then(function(data) {
            $scope.data = data;
            angular.forEach ($scope.data , function (d) {
                angular.forEach (d.equipments, function (e) {
                    // Change this line
                    $scope.allEquipments.push(e);
                    console.log($scope.allEquipments);
                })
            });
            console.log($scope.data);
        }).catch(function(error) {
            $scope.error = error;
        });
}]);

您的ng-repeat

 <tr data-ng-repeat="d in allEquipments">
    <td headers = "system">System</td>
    <td headers = "equipment" >{{d.equipment}}</td>
    <td headers = "date">date</td>
    <td headers = "type">Standby</td>
 </tr>