How to bind data of firebase with angularJS scope

问题: 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...

问题:

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?


回答1:

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:


回答2:

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>

  • 发表于 2018-07-07 00:16
  • 阅读 ( 278 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除