我正在尝试将 Firebase 和 AngularFire 用于我正在构建的应用程序。诚然,我是 Angular 和 Firebase 的新手,因此我们将不胜感激。
我在 Firebase 中有以下数据库结构:
- 史诗
- 史诗 1
- ID
- 标题等
- 史诗 2
- ID
- 标题等
- 史诗 1
用户
用户 1
-activeepics
活跃史诗 1
活跃史诗2
在下一页上,我对数据库中的每个史诗都有一个 ng-repeat。每个史诗都有一排按钮,其中一个给我带来了麻烦。如果当前用户已经开始了史诗(例如史诗出现在该用户的“活动史诗”中),那么按钮应该说“Tap Out”。如果史诗不在用户的活动史诗中,则应显示“开始”。
按钮在单击时应该执行不同的操作,具体取决于按钮标签。因此,如果按钮标签显示“开始”,应用程序应将史诗添加到当前用户的“活动史诗”中,并将按钮标签更改为“Tap Out”。相反,如果按钮标签是“Tap Out”,应用程序应该从“activeepics”中删除史诗,并将按钮标签改回“开始”。
但是,我得到了各种奇怪的行为。当我使用 1 或 0 等虚拟 ID 时,该应用程序会显示正确的按钮标签。但是,当我添加具有 Firebase 生成 ID 的史诗时,所有标签都会重置为“开始”。我还注意到,该应用程序多次循环遍历每个史诗(我为每个显示的史诗输入了调试 console.log)。
我认为问题可能是在将 Firebase 数据绑定到 $scope 后我有多个承诺对象。如果可以的话请帮忙!
这是代码:
看法
<div ng-repeat="(name,epic) in epics | filter:search | orderBy:order | filter:{category:category}" class="epic">
<div>
<div class="small-block-grid-3 epicActions">
<li><a href="#"> Remix </a></li>
<li><a href="#/share"> Share </a></li>
<li><a href="#" ng-click="handleLabel(name)" prevent> {{getLabel(name)}} </a></li>
</div>
</ul>
</div>
</div>
控制器
$scope.desiredUser = UserService.getCurrentUser();
var ref = new Firebase("https://epicly.firebaseio.com/epics");
angularFire(ref, $scope, 'epics');
var ref2 = new Firebase("https://epicly.firebaseio.com/users");
angularFire(ref2, $scope, 'users').then(function(){
for (var i = 0; i<$scope.users.length; i++){
if($scope.users[i].email === $scope.desiredUser){
$scope.currUser = $scope.users[i];
}
}
var ref3 = new Firebase("https://epicly.firebaseio.com/users/" + $scope.currUser.id + "/activeepics");
angularFire(ref3, $scope, 'activeEpics').then(function(){
console.log($scope.activeEpics);
$scope.getLabel = function(epic){
console.log(epic);
for(var i = 0; i < $scope.activeEpics.length; i++){
if ($scope.activeEpics[i].id === epic) {
return "Tap Out";
}
}
return "Start";
}
$scope.handleLabel = function(name){
var label = $scope.getLabel(name);
if(label === "Tap Out"){
//remove from active epics
} else {
//add to activeepics
$scope.toAdd = {"id": name}
$scope.activeEpics.push($scope.toAdd);
}
}
});
});