1

Hi how can i bind data that i received from firebase with scope in angularJS. I am new to this and following though w3school. So i am not sure what i am missing. I am using

"angular": "^1.7.2",
"angular-route": "^1.7.2",
"firebase": "^5.2.0",

And my code is like this

app.config(function($routeProvider){
  $routeProvider
  .when('/',{
    templateUrl:'home.html',
    controller:'UserController'
  })
})
app.controller("UserController",  function ($scope, $routeParams, $location) {
    firebaseRef.child('users').on("value", function(response) {
      $scope.userCount=response.numChildren();
  });
})

And in html i am doing like this

<html lang="en" ng-app="my-first-app">
............<HEADER AND TITLE  AND BODY>......
    <h3>User count : {{userCount}} </h3>
</body>
</html>

But nothing is coming even though if I console.log the value of response.numChildren() I see 4.

Can anyone please tell me where I'm doing wrong?

2
  • Can you show the complete user html view? Commented Jul 5, 2018 at 19:15
  • @MarcusHöglund, yes i added the html Commented Jul 5, 2018 at 19:19

2 Answers 2

2

By the time your Firebase on("value" callback is invoked, AngualarJS is not expecting changes to the HTML anymore. So you have to explicitly tell it that you're changing the HTML, by using $apply() or $timeout():

app.controller("UserController",  function ($scope, $routeParams, $location) {
    firebaseRef.child('users').on("value", function(response) {
      $timeout(function() {
        $scope.userCount=response.numChildren();
      });
  });
}

Also see:

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you :)) that worked. Seems like something synch and asynchronous behavior of typescript
0

You need to add the ng-view to the view.

Try it like this

var app = angular.module("my-first-app",["ngRoute"]);
app.config(function($routeProvider){
  $routeProvider
  .when('/',{
    template:'<h3>User count : {{userCount}} </h3>',
    controller:'UserController'
  })
})
app.controller("UserController",  function ($scope, $routeParams, $location) {
    $scope.userCount = 3;
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular-route.min.js"></script>

<div ng-app="my-first-app">
    <div ng-view></div>
</div>

2 Comments

Yes i have added that,, but still the value is not coming.
@user7747472 updated my answer with an example of how to route the html correctly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.