javascript - DOM 中的 $scope 值为 null

标签 javascript angularjs firebase angularfire angular-routing

我正在尝试将 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');
    }

}
]);

最佳答案

三件事。

  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,您的 Controller 代码将大大简化。

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

关于javascript - DOM 中的 $scope 值为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34028655/

相关文章:

javascript - AngularJS - 根据另一个 md-autocomplete 输入自动更新 md-autocomplete 搜索列表

javascript - 修改以下排序函数,使其返回数字

angularjs - Protractor 与 IDE 集成

c# - 如何将标签值作为参数传入 javascript 函数?

c# - 如何将服务器 session 从 Razor MVC C# 传递到 Angularjs?

android - 如何将数据字段保存到 Firebase 用户输入

Firebase 托管 SPA 的 : How to prevent caching for the index. html

android - 检查字段数据是否更改而不是子数据中的任何字段

javascript - 从 php 传递数组作为 javascript 函数参数

javascript - 等待 Block/Promise/Fetch 将 JSON 数据传递给 Svelte 组件