1
我寫了一個顯示帖子列表的離子頁面,每個帖子都有一個用於標記它的收藏按鈕(星形圖標)。當我點擊收藏按鈕時,數據將被插入到數據庫中,但圖標不會立即標記。重新加載頁面後,它被標記。所以點擊它時如何使圖標立即標記。製作收藏夾按鈕顯示標記不帶重新加載頁面Ionic
這裏是我的網頁代碼,它使用$scope.post_infos
顯示數據,如果變量「標記」的存在,最喜歡的按鈕,將顯示星形圖標,否則概述星形圖標:
<ion-list> //ng-controller is recuitmentCtrl
<div ng-repeat="post_info in post_infos" >
<ion-item>
<div class=" item-button-right">
<a ng-click="showContent(post_info.id)">
<div class="post">
<div class= "title">{{post_info.title}}</div>
<div class= "description">{{post_info.description}}</div>
</div>
</a>
<button class="button button-icon i" ng-click="isFavorite(post_info.id)">
<i ng-class="{'icon ion-android-star-outline': !post_info.marked,
'icon ion-android-star': post_info.marked}"></i>
</button>
</div>
</ion-item>
</div>
</ion-list>
在我controller.js
.controller('recuitmentCtrl', ['$scope', '$state', function ($scope, $state,) {
var ref = firebase.database().ref('posts');
var titles, descriptions;
$scope.post_infos = [];
ref.on('value' ,function(snapshot){
var userID = firebase.auth().currentUser.uid;
$scope.post_infos = [];
snapshot.forEach(function(childSnapshot){
var marked = firebase.database().ref('users/'+ userID + '/favorites/' + childSnapshot.key);
marked.on('value', function(snapshot_user){
var obj = {
"id": childSnapshot.key,
"title": childSnapshot.val().title,
"description": childSnapshot.val().description,
"marked": snapshot_user.child("marked").val()
};
$scope.post_infos.push(obj);
})
});
});
$scope.showContent = function(param){
$state.go('postdetail',{postID: param});
};
$scope.isFavorite = function(postID){
var userID = firebase.auth().currentUser.uid;
var userRef = firebase.database().ref('users/'+ userID + '/favorites/' + postID);
userRef.set({
marked: true
}).then(function(result){
});
}
}])
這裏是我的數據庫:
它像一個魅力。我嘗試了兩條註釋行,兩者都起作用,但它也添加了我在列表底部點擊的帖子。因此,我將marked.on(「value」)更改爲maked.once(「value」)。完善!!。非常感謝!! – ThinhPhan
嗨mcrvaz,我做了你說的和它的工作,但現在當我發佈一篇新文章時,我面臨着一個關於ref.on('value')的新問題。我想你可以在不看到我的postController代碼的情況下理解它是什麼,我的postController將發佈一篇新文章,點擊提交時,它會重定向到上面的頁面。這裏的問題是列表中的每個帖子顯示兩次,但是如果我評論*變量標記爲*的所有行,它將起作用。也許它與回調有關,我嘗試了一些ref.off,但它沒有幫助。請問你能幫幫我嗎! – ThinhPhan
看來你正在觀察'ref.on('value')'的變化,並且每次將值更改爲 '$ scope.post_infos.push(obj);'時將新的'post_info'推入列表。 也許你可以在添加列表之前檢查'post_info'是否已經存在,或者只是更新列表上的值而不是添加新列表中的值。 – mcrvaz