Firebase和Angularjs Scope对象数组未定义

时间:2017-08-09 09:27:48

标签: javascript angularjs arrays firebase angularjs-scope

我正在尝试使用angularjs显示对象。但是在html中它看起来是未定义的。

app1.controller('ctrl1' , function($scope){ 
  categories = [];
  var dbRef = firebase.database().ref().child('Categories/');
  dbRef.once('value', snap => {

    snap.forEach(function(childSnap) {
      //CATEGORY MODEL
       var category = {
            name : "",
            id  : "",

            subCategories: {
              name: "",
              id: ""
            }

        };
      category.id = childSnap.val().id
      category.name = childSnap.val().name
      category.subCategories = childSnap.val().subCategories
      categories.push(category)
    })

  }).then(() => {
    $scope.allcats = categories;
  });
});

和html

 <div id="nav-aside " class="nav" ng-controller="ctrl1">
              {{allcats}}
            <ul class="nav-aside-list" ng-repeat="categories in allcats">
              <li><span></span><a href="#">{{categories.name}}</a></li>
            </ul>
          </div>

这不起作用。有谁可以提供帮助? 提前致谢!

1 个答案:

答案 0 :(得分:0)

将您的代码更改为:

app1.controller('ctrl1' , function($scope){ 
      $scope.allcats = [];
      var dbRef = firebase.database().ref().child('Categories/');
      dbRef.once('value', snap => {

        snap.forEach(function(childSnap) {
          //CATEGORY MODEL
           var category = {
                name : "",
                id  : "",

                subCategories: {
                  name: "",
                  id: ""
                }

            };
          category.id = childSnap.val().id
          category.name = childSnap.val().name
          category.subCategories = childSnap.val().subCategories
          $scope.allcats.push(category);
          $scope.$apply();
        })

      }).then(() => {
        console.log($scope.allcats);
      });
    });