Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase binding not being reflected in Angular view

I am pulling out one value from every object in Firebase, picUrl (the url of a picture) and storing that in a scope array variable, $scope.bricks. How do I make it so $scope.bricks updates everytime Firebase is updated with a new object, and therefore new picUrl? Thanks in advance!

angular.module('noorApp').controller('MainCtrl', function ($scope, $http, $firebase) {
    var sync = $firebase(ref);
    var firebaseObj = sync.$asObject();
    $scope.bricks = [];

    firebaseObj.$loaded().then(function(){
        angular.forEach(firebaseObj.products, function(value, key){
            $scope.bricks.push({src: value.picUrl});
        });
    });
});

EDIT:

I should have posted how I'm using $scope.bricks in the DOM.

<div class="masonry-brick" ng-repeat="brick in bricks">
  <img ng-src="{{ brick.src }}">
</div>

The issue is that while firebaseObj is synced with Firebase, $loaded() is only running once.
Thanks.

like image 935
user3527354 Avatar asked Jul 27 '26 17:07

user3527354


1 Answers

As I said in my comment, you can probably get it working by:

    firebaseObj.$loaded().then(function(){
        angular.forEach(firebaseObj.products, function(value, key){
            $scope.bricks.push({src: value.picUrl});
            $scopy.$apply();
        });
    });

Update: the above doesn't work, see OP's comment below.

To learn more about $scope.$apply read this article: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

But even though this may fix your current issue, you'll run into other problems later. The reason for this is that you're creating an "unmanaged array" of bricks. AngularFire has quite some code to ensure that Firebase's order collections and AngularJS's two-way data-bound arrays play nice together.

For this reason it is probably better if you set up a separate sync for your array of products:

angular.module('noorApp').controller('MainCtrl', function ($scope, $http, $firebase) {
    var sync = $firebase(ref);
    var firebaseObj = sync.$asObject();
    $scope.bricks = $firebase(ref.child('products')).$asArray();    
});

With this setup, AngularFire will call $apply() automaticaly when the array items initially load or are modified afterwards.

like image 109
Frank van Puffelen Avatar answered Jul 30 '26 09:07

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!