【问题标题】:How to bind data of firebase with angularJS scope如何将firebase的数据与angularJS范围绑定
【发布时间】:2018-07-05 19:11:04
【问题描述】:

您好,如何将我从 firebase 收到的数据与 angularJS 中的范围绑定。 我是新来的,尽管w3school。所以我不确定我错过了什么。 我正在使用

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

而我的代码是这样的

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

而在 html 中我是这样做的

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

但是即使我console.logresponse.numChildren() 的值我看到了4,什么也不会发生。

谁能告诉我哪里做错了?

【问题讨论】:

  • 你能显示完整的用户 html 视图吗?
  • @MarcusHöglund,是的,我添加了 html

标签: javascript angularjs firebase firebase-realtime-database


【解决方案1】:

当您的 Firebase on("value" 回调被调用时,AngualarJS 不再期望对 HTML 进行更改。因此,您必须使用$apply()$timeout() 明确告诉它您正在更改HTML:

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

另见:

【讨论】:

  • 谢谢 :)) 成功了。似乎是打字稿的同步和异步行为
【解决方案2】:

您需要将 ng-view 添加到视图中。

这样试试

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>

【讨论】:

  • 是的,我已经添加了,但价值仍然没有到来。
  • @user7747472 用如何正确路由 html 的示例更新了我的答案
猜你喜欢
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
  • 2018-03-02
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 2012-09-06
  • 1970-01-01
相关资源
最近更新 更多