【发布时间】:2015-10-09 21:55:55
【问题描述】:
我正在尝试实现一个简单的收藏夹系统。在页面加载帖子上列出在主页上,任何以前收藏的名为 nubs 的帖子都将显示在它们下方的 FAVED 标签。
<div class="list-group" ng-repeat="nub in nubs">
<a href="#" class="list-group-item active">
<h4 class="list-group-item-heading">{{nub.title}}</h4>
<p class="list-group-item-text">{{nub.description}}</p>
<p class="list-group-item-text">{{nub.synopsis}}</p>
<li ng-repeat="url in nub.attachmentsUrls">
<p class="list-group-item-image">
<img ng-src={{url}} />
</p>
</li>
</a>
<button ng-click="toggleFav(nub)">favorite</button>
<p ng-show="getFaved(nub.$id)">FAVED</p>
</div>
这是可行的,但是当我将某些内容添加到我的收藏夹时,页面不会更新以反映新收藏的帖子。我想让我的页面积极响应 toggleFav 功能。
这是我的控制器
var ref = new Firebase("https://xxxxx.firebaseio.com");
var auth = ref.getAuth();
var nubRef = new Firebase("https://xxxxx.firebaseio.com/Nubs");
var nubs = $firebaseArray(nubRef);
$scope.nubs = nubs;
var userRef = new Firebase("https://xxxxx.firebaseio.com/users");
var users = $firebaseArray(userRef);
$scope.users = users;
// Array of booleans for favorites
$scope.favedArray = [];
// Array of user ids for
$scope.userIdArray = [];
var userFavs = $firebaseArray(userRef.child(auth.uid).child("favorites"));
$scope.userFavs = userFavs;
userFavs.$loaded()
.then
(
function()
{
nubs.$loaded()
.then
(
function()
{
$scope.tempFaved = [];
$scope.tempId = [];
console.log(userFavs);
angular.forEach
(
nubs,
function(nub)
{
$scope.tempFaved.push(false);
$scope.tempId.push(nub.$id);
console.log($scope.tempId);
angular.forEach
(
userFavs,
function(favs)
{
console.log($scope.tempFaved);
if(favs.nub == nub.$id)
{
$scope.tempFaved.pop();
$scope.tempFaved.push(true);
console.log($scope.tempFaved);
}
}
);
}
);
while($scope.tempFaved.length > 0)
{
$scope.favedArray.push($scope.tempFaved.pop());
$scope.userIdArray.push($scope.tempId.pop());
}
$scope.getFaved = function(nubId)
{
console.log($scope.favedArray[$scope.userIdArray.indexOf(nubId)]);
$scope.faved = $scope.favedArray[$scope.userIdArray.indexOf(nubId)];
return $scope.faved;
}
$scope.toggleFav = function(nub)
{
var nubFavRef = nubRef.child(nub.$id).child("favorites");
var nubFavs = $firebaseArray(nubFavRef);
var faved = $scope.getFaved(nub.$id)
console.log(faved);
if (faved == false)
{
nubFavs.$add
(
{
user: auth.uid
}
);
userFavs.$add
(
{
nub: nub.$id
}
)
console.log("favorited");
}
else
{
nubFavs.$remove(auth.uid);
userFavs.$remove(nub.$id);
console.log("unfavorited");
}
};
}
)
}
);
本质上,它循环浏览页面上显示的小块或帖子,并根据用户收藏的小块检查它们以显示 FAVED 标签并切换收藏按钮的功能。如果用户没有收藏小块,该按钮会将小块添加到他们的收藏列表中,并将它们添加到收藏小块的用户列表中,如果用户确实收藏了帖子,它将删除它们。
toggleFav 的不受欢迎的功能也不起作用,因此也将不胜感激,但这是能够访问我不知道该怎么做的最喜欢的数组的正确子项的问题。
我认为当某些东西被收藏时,页面需要更新正确的信息是某种 $on 监听器,但我不知道如何实现它。
【问题讨论】:
-
很确定你需要留意变化。或者试试 AngularFire:firebase.com/docs/web/libraries/angular/quickstart.html
-
$firebaseArray.$loaded仅在加载初始数据时触发一次。对基础数据的任何后续更改都不会触发$loaded。当$loaded触发时,您应该扩展$firebaseArray,而不是修改数组。见firebase.com/docs/web/libraries/angular/guide/…
标签: javascript html angularjs firebase angularfire