使最喜欢的按钮显示标记而无需重新加载页面 Ionic

Make favorite button shows marked without reloading page Ionic

我写了一个显示 post 列表的 Ionic 页面,每个 post 都有一个收藏按钮(星形图标)供用户标记。当我点击一个收藏夹按钮时,数据将被插入到数据库中,但图标并没有立即被标记出来。重新加载页面后,它被标记。那么如何让图标在点击的时候立刻被标记呢

这是我的页面代码,它使用$scope.post_infos显示数据,如果变量"marked"存在,收藏按钮将显示星形图标,否则轮廓星形图标:

<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){
    });
}

}])

这是我的数据库:

当变量 post_info 被标记为收藏时,您需要更新它,有两种方法可以做到:

控制器

$scope.isFavorite = function(post){
   var userID = firebase.auth().currentUser.uid;
   var userRef = firebase.database().ref('users/'+ userID + '/favorites/' + post.id);
   //post.marked = true; //instant feedback
   userRef.set({
      marked: true
   }).then(function(result){
       //post.marked = true; //will mark as favorite as soon as the server accepts the request
   });

模板

<button class="button button-icon i" ng-click="isFavorite(post_info)">
         <i ng-class="{'icon ion-android-star-outline': !post_info.marked, 
                    'icon ion-android-star': post_info.marked}"></i>
</button>