$ scope значение равно нулю в DOM

0

Я пытаюсь использовать ng-repeat с AngularJS, но я не получаю результат своей области в своем DOM. Может ли кто-нибудь увидеть эту проблему? Я пытаюсь устранить эту проблему часами и часами, а "игроки" всегда равны нулю.

Вот мой 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');
    }

}
]);
  • 0
    Вы можете поделиться PLNKR или скрипкой?
  • 0
    Да вот скрипка, jsfiddle.net/pxn44hzw/#&togetherjs=HNvlaOkhoU
Показать ещё 1 комментарий
Теги:
firebase
angular-routing
angularfire

1 ответ

1
Лучший ответ

Три вещи.

  1. С обычным Firebase SDK Angular не знает, когда запускать $digest.
  2. Используйте $firebaseArray() вместо того, чтобы манипулировать своим.
  3. Используйте resolve() в маршрутизаторе, чтобы ввести пользователя с помощью $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);
});
  • 0
    Дэвид Ист, Большое спасибо, я работал над этим до полуночи вчера вечером и все утро сегодня. Это решило это.
  • 1
    Пун намеревался :)?

Ещё вопросы

Сообщество Overcoder
Наверх
Меню