Nader Nader - 27 days ago 11
AngularJS Question

AngularJS not showing data when promise resolves

My table won't display the data it receives after a promise resolves. The data, however, is shown after a filter query is updated.

Angular:

let app = angular.module("tierlist", []);

app.controller("tierListController", function ($scope, $http) {


firebase.database().ref('/Primaries/').once('value').then(function (snapshot) {
console.log(snapshot.val());

$scope.Primaries = $.map(snapshot.val(), function (element) {
return element;
});
console.log($scope.Primaries);
});

});


HTML:

<div class="container tiertab" id="Primaries">
<table id="primariesTable" class="table table-condensed table-responsive sortable">
<thead>
<tr>
<th onclick="sortTable('primariesTable', 0)">Rank</th>
<th onclick="sortTable('primariesTable', 1)">Weapons</th>
<th onclick="sortTable('primariesTable', 2)">Primary DMG Type</th>
<th onclick="sortTable('primariesTable', 3)">CC Mechanic</th>
<th onclick="sortTable('primariesTable', 4)">MR Req</th>
<th>Notes</th>
<th>Base or Event Rankings</th>
<th>Suggested Builds</th>
</tr>
</thead>
<tbody>
<tr class="sortable" ng-repeat="primary in Primaries | filter: $ctrl.query" >
<td>{{primary.rank}}</td>
<td>{{primary.name}}</td>
<td>{{primary.damage}}</td>
<td>{{primary.cc}}</td>
<td>{{primary.mr}}</td>
<td>{{primary.notes}}</td>
<td>{{primary.event}}</td>
<td>{{primary.builds}}</td>
</tr>
</tbody>
</table>
</div>


I believe I'm doing something wrong as far as the controller is involved. If the data is associated with the given fields, why would the data not display after resolving the promise?

Answer Source

When $scope bound data is updated asynchronously angular doesn't update the view because it doesn't know when this is going to happen. Your data could be being updated when filtering since angular is internally triggering $scope.$digest(). You could try:

$scope.$evalAsync(function () {
    $scope.Primaries = $.map(snapshot.val(), function (element) {
        return element;
    });
});

This should update the view. $evalAsync was introduced in angularjs 1.2 but you can use $scope.$apply if the version you are using is older. This post has great info on the difference between both: https://stackoverflow.com/a/23102223/7083204