最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ng-class not refresh when data change - Stack Overflow

programmeradmin1浏览0评论

I want to change the color item whan my data change. I use this template code:

<ion-view view-title="Evénement" class="content">
    <ion-content class="padding">
         <ion-list>
            <ion-item ng-repeat="myuser in users">
                <span>{{myuser.user_name}} </span><a class="button button-icon icon ion-person-add icon_add" ng-click="addContact('{{myuser.id}}')" ng-class="{contact_added : myuser.isContact }"></a>
            </ion-item>
        </ion-list>
    </ion-content>
</ion-view>

I want to change the color item whan my data change. I use this template code:

<ion-view view-title="Evénement" class="content">
    <ion-content class="padding">
         <ion-list>
            <ion-item ng-repeat="myuser in users">
                <span>{{myuser.user_name}} </span><a class="button button-icon icon ion-person-add icon_add" ng-click="addContact('{{myuser.id}}')" ng-class="{contact_added : myuser.isContact }"></a>
            </ion-item>
        </ion-list>
    </ion-content>
</ion-view>

I use firebase to loading and saving data. So, I use this code for synchronizing data.

ref.child('contact').child(authData.uid).on('child_added', function (snapshot) {
        var myUser = snapshot.key();
        $scope.users.push(myUser);
    });

When I add a contact on firebase, my color icon does not change immediately. I must click and move my mouse on html page to update the color.

How I have to do to refresh instantly my icon when the data change?

Share Improve this question edited Feb 12, 2016 at 14:02 David East 32.7k6 gold badges69 silver badges83 bronze badges asked Feb 12, 2016 at 9:07 user3884677user3884677 4136 silver badges26 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Don't use $scope.$apply(), use AngularFire.

Angular apps should not have to manage the digest loop. Firebase directly integrates with Angular with the AngularFire library, which manages data synchronization and the triggering of $digest.

In your case you can create a $firebaseArray to synchronize your changes:

angular.module('app', ['firebase'])
  .constant('FirebaseUrl', '<my-firebase-app>')
  .service('rootRef', ['FirebaseUrl', Firebase])
  .controller('MyCtrl', MyController);

function MyController($scope, rootRef, $firebaseArray) {
  var userRef = rootRef.child('contact').child(authData.uid);
  $scope.users = $firebaseArray(userRef);
}

The advantage of using AngularFire is two fold. Firstly, you don't have to manage $scope.$apply(). Secondly, you get realtime array synchronization for free.

add $scope.$apply(); after $scope.users.push(myUser); line.

发布评论

评论列表(0)

  1. 暂无评论