我在 Firebase 应用中使用 AngularJS,并且有一个函数可以执行一些内部联接来获取一些数据。更多 details here 。从 firebase api 获取响应后,我创建一个对象并将其插入数组(作用域变量)中。我在调试中看到数据已被检索并且 $scope 变量已正确填充。问题是它没有显示在 ng-repeat 中。
我的功能:
$scope.getMessagesByRegion = function(regionId){
console.log('Function start');
var rootRef = firebase.database().ref();
var regionMessagesRef = rootRef.child("region_messages/"+ regionId);
$scope.messages_by_region = []; // Here I reset the scope variable
regionMessagesRef.on('child_added', function(rmSnap) {
var messageRef = rootRef.child("messages/"+rmSnap.key);
messageRef.once('value').then(function(msgSnap){
var msg = {
key : msgSnap.key,
name : msgSnap.val().name,
type : $scope.getTypeName(msgSnap.val().type),
show_only_once : rmSnap.val().show_only_once,
pre_requisite_message : rmSnap.val().pre_requisite_message
}
console.log(msg); // here I see the object in the console. it is OK
$scope.messages_by_region.push(msg); // pushing the item
console.log('----------------');
console.log($scope.messages_by_region);
})
});
}
我的 HTML:
<table class="table">
<thead>
<tr>
<th>Message name</th>
<th>Type</th>
<th>Show only once</th>
<th>Pre requisite</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="msg in messages_by_region">
<td ng-bind="msg.name"></td>
<td ng-bind="msg.type"></td>
<td ng-bind="msg.show_only_once"></td>
<td ng-bind="msg.pre_requisite_message"></td>
</tr>
</tbody>
</table>
这是我在控制台中看到的内容:
问题是,即使数组中有一个对象,它也不会显示在 View 中。就像为 $scope.messages_by_region
变量设置了一个空数组
我很难弄清楚我做错了什么。你能看出我的函数出了什么问题吗?
感谢您的帮助。
最佳答案
尝试,
$scope.$apply(function(){
$scope.messages_by_region.push(msg);
});
或者,
$scope.messages_by_region.push(msg);
$scope.$apply();
关于javascript - AngularJS:2 路绑定(bind)的奇怪行为(ng-repeat),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41106439/