$scope 值在 DOM 中为空

$scope value is null in DOM

我正在尝试将 ng-repeat 与 AngularJS 一起使用,但我没有在我的 DOM 中得到范围的结果。任何人都可以看到这个问题吗?我已经尝试解决这个问题好几个小时了,但 "players" 始终为空。

这是我的 html:

<body ng-controller="CoachCtrl" >

<div class="mdl-tabs mdl-js-tabs mdl-js-ripple-effect">
  <div class="mdl-tabs__tab-bar">
      <a href="#coach" class="mdl-tabs__tab is-active">Starks</a>
      <a href="#lannisters-panel" class="mdl-tabs__tab">Lannisters</a>
      <a href="#targaryens-panel" class="mdl-tabs__tab">Targaryens</a>
  </div>

  <div class="mdl-tabs__panel is-active" id="coach" >
    <p>Number of players {{ players.length }}</p>
    <table class="table">
      <tr>
          <th>Firstname
          </th>
          <th>Lastname
          </th>
          <th>Tryout Date
          </th>
      </tr>
      <tr ng-repeat="kid in players" >
          <td>{{ kid.firstname }}
          </td>
          <td>{{ kid.lastname }}
          </td>
          <td>{{ kid.tryout_date }}
          </td>
      </tr>
    </table>
  </div>
</div>

这是我的 js:

'use strict';
 
angular.module('myApp.coach', ['ngRoute', 'firebase'])
 
// Declared route 
.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/coach', {
        templateUrl: 'coach/coach.html',
        controller: 'CoachCtrl'
    });
}])

// Home controller

.controller("CoachCtrl", ["$scope", "$firebaseAuth", "$location",
  function($scope, $firebaseAuth, $location) {
    var ref = new Firebase("https://intense-heat-2545.firebaseio.com");
    var authData = ref.getAuth();
    if(authData){
     console.log("User is "+authData.uid+" and is logged in with "+authData.provider);
     var league = new Firebase("https://intense-heat-2545.firebaseio.com/users/"+authData.uid+"/league");
      league.on("value", function(snapshot){
       console.log("League ID = "+snapshot.val());
       var leagueVal = snapshot.val();
       var playerlist = new Firebase("https://blahblah.firebaseio.com/"+leagueVal+"/players");
       $scope.players = [];
                $scope.players.push({firstname:'John', lastname:'B', tryout_date:'2015-11-30'});
                $scope.players.push({firstname: 'Marty', lastname: 'B', tryout_date: '2015-12-01'});
                playerlist.on("child_added", function(snapshot){
                    //console.log("players ="+snapshot.val());
                    var player = snapshot.val();
                    console.log("Firstname ="+player.firstname);
                    var first = player.firstname;
                    var last = player.lastname;
                    var tyd = player.tryout_date;
                    console.log('player data ='+first+last+tyd);

                    $scope.players.push({ firstname: first, lastname: last, tryout_date: tyd });
                    var len = $scope.players.length;
                    for (var i = 0; i < len; i+=1){
                        if (1 === len){
                            console.log("player name = "+$scope.players[i].firstname);
                        }
                        
                    }
                    
                    console.log("players len ="+$scope.players.length);

                }, function(error){
                    console.log("Error getting player info: "+error.code);
                });


       console.log("players ="+$scope.players[1].firstname+" len= "+$scope.players.length);
       
      }, function(error){
       console.log("Erro ="+error.code);
      });
    } else {
     console.log("User is not logged in.");
     $location.path('/signin');
    }

}
]);

三件事。

  1. 使用常规 Firebase SDK Angular 不知道何时 运行 $digest
  2. Use $firebaseArray() rather than manipulating your own.
  3. Use resolve() in the router to inject the user with $firebaseAuth().$waitForAuth().

-

  var rootRef = new Firebase("https://<my-firebase-app>.firebaseio.com");
  var leagueRef = rootRef.child("users").child(authData.uid).child("league");
  // read it one time
  leagueRef.once('value', function(snap) {
     var leagueVal = snapshot.val();
     var playerList = rootRef.child(leagueVal).child("players");
     // $firebaseArray() will synchronize child events into an array
     // Each update will know how to update $digest as well, which
     // will keep the view updated.
     $scope.players = $firebaseArray(playerList);
  });  

如果您在路由器中使用 resolve,您的控制器代码将大大简化。

.constant('FBURL', '<my-firebase-app>')

.service('RootRef', ['FBURL', Firebase)

.factory('Auth', function($firebaseAuth, RootRef) {
  return $firebaseAuth(RootRef);
})

.factory('UserLeague', function(RootRef) {
  return function(uid) {
    var leagueRef = RootRef.child("user").child(uid).child("league");
    var deferred = $q.defer();
    leagueRef.once(function(snap) {
      deferred.resolve(snap.val());
    });
    return deferred.promise;
  }
})

.config(function($routeProvider) {
    $routeProvider.when('/coach', {
        templateUrl: 'coach/coach.html',
        controller: 'CoachCtrl',
        resolve: {
          leagueVal: function(UserLeague, Auth) {
            var authData = Auth.$getUser();
            return UserLeague(authData.uid);
          },
          authData: function(Auth) {
            return Auth.$waitForAuth();
          }
        }
    });
})

.controller("CoachCtrl", function($scope, leagueVal, authData, RootRef) {
   // no need to check for a user because authData is injected
   // use the resolved leagueVal to create a ref
   var playerList = RootRef.child(leagueVal).child("players");
   // synchronize the players to an array 
   $scope.players = $firebaseArray(playerList);
});