【问题标题】:push into an array console log can see but won't render in html why? angularJS推入数组控制台日志可以看到但不会在html中呈现为什么?角JS
【发布时间】:2017-02-02 13:31:06
【问题描述】:

我有一个可以工作的测试数据库,当我使用console.log 时,我可以看到这些对象,但是当我尝试在 html 中呈现时。为什么显示为空?

我的角码

var app = angular.module('startBet',['firebase']);
var ref = new Firebase("https://vsw.firebaseio.com");

app.controller("ibet", function($scope, $firebaseObject) {
   $scope.todos = [{act: 'complete', test: 'abc'},
        {act: 'not', test: 'bdb'}];

    $scope.bets = [];

    var ref2 = new Firebase("https://vsw.firebaseio.com/bets");
    ref2.once("value", function(snapshot) {
      snapshot.forEach(function(childSnapshot) {
        var key = childSnapshot.key();
        var childData = childSnapshot.val();
        $scope.bets.push(childData);
        $scope.todos.push(childData);
      });
    });

    console.log($scope.todos);
    console.log($scope.bets);

我的html

    <div class="bot-container" ng-app='startBet'>
        <div class="in-play" ng-controller='ibet'>
            <header><p>{{todos.length}}</p></header>
            <div class="bets-list">
                <div class="bet-title">
                    {{bets.length}}
                </div>

抱歉,有任何结束标签。懒得抄别人 我可以看到我硬编码的长度为 2,它以 html 呈现,而另一个长度为 0。

但是在 console.log 中,我可以看到显示所有对象而不是任何内容,或者只是这两个硬编码。

我在这里错过了什么?

提前致谢。

【问题讨论】:

    标签: javascript angularjs arrays object push


    【解决方案1】:

    您需要使用ng-repeat 来迭代列表:

    <ul>
        <li ng-repeat="td in todos">{{td.act}}</li>
    </ul>
    

    【讨论】:

      【解决方案2】:

      对 Firebase 请求的回调可能不会触发要运行的摘要循环,因此您的 DOM 没有更新。尝试将代码包装在$timeout 中,这将触发一个摘要循环。 (更详细的解释请参见this。)

      app.controller("ibet", function($scope, $firebaseObject, $timeout) {

      ...

      var ref2 = new Firebase("https://vsw.firebaseio.com/bets");
      ref2.once("value", function(snapshot) {
          $timeout(function() {
              snapshot.forEach(function(childSnapshot) {
                  var key = childSnapshot.key();
                  var childData = childSnapshot.val();
                  $scope.bets.push(childData);
                  $scope.todos.push(childData);
              });
          });
      });
      

      您可能希望使用 AngularFire 而不是常规的 Firebase JavaScript API。

      【讨论】:

        猜你喜欢
        • 2014-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多