我有多个型号,但有一个控制器。我的控制器处理一个视图的更新。在那个视图中,我展示了三个部分,包括计算游戏玩法,排名和游戏结果。我只打了一个电话来发布游戏的结果,我得到了在数据库中正确更新的所有内容,但唯一的帖子更新是游戏结果。我被迫使用window.location.reload()来刷新所有内容,这似乎不是正确的方法。我打电话给//////////打电话给REFRESH /////////window.location.reload()
非常感谢任何帮助。
我的控制器
(function(){
angular.module('Dashboard',['Games'])
.controller('dashboardController', ['$http', 'GameService','TournamentService', 'Stats', 'ProgressGrid', function($http, GameService, TournamentService,Stats, ProgressGrid) {
var vm = this;
vm.isEditing = false;
vm.newGame = {
awayTeam: '',
homeTeam: '',
homeTeamScore: 0,
awayTeamScore: 0
};
vm.showModal = function() {
vm.isEditing = true;
}
vm.hideModal = function() {
vm.isEditing = false;
vm.addGameForm.$setPristine();
vm.isSaving = true;
}
vm.addGame = function() {
vm.isSaving = true;
vm.newGame.id = vm.games.length + 1;
// vm.newGame.gameDate = dateTransform(vm.newGame.gameDate);
// get team name for notification
vm.getTeamName = function(id) {
return vm.teams[id-1].teamName
}
GameService.save(vm.newGame, function() {
vm.addGameForm.$setPristine();
// set var for overtime
overtime = '';
if(vm.newGame.hadOT == true){
overtime = "(OT)";
}
if(vm.newGame.hadSO == true){
overtime = "(SO)";
}
vm.games = GameService.query();
vm.hideModal();
////////// CALL TO REFRESH /////////
window.location.reload();
})
}
var data = TournamentService.then(function(data) {
vm.tournament = data.tournament
vm.games = data.games;
vm.hipchatroom = vm.tournament.hipchatroom;
vm.hipchatkey = vm.tournament.hipchatkey;
vm.teams = vm.tournament.teams
vm.numberOfTeams = vm.teams.length;
vm.totalGames = ((vm.numberOfTeams -1) * 2) * vm.numberOfTeams
vm.percentGamesPlayed = (vm.games.length * 100) / vm.totalGames;
vm.progressGrid = ProgressGrid.init(vm.numberOfTeams);
Stats.calculateStandings(vm.games, vm.teams, vm.progressGrid);
});
vm.getTeamName = function(id) {
return vm.teams[id-1].teamName
}
}])
.factory('Stats', function() {
var calc = {
calculateStandings: function(games, teams, progressGrid) {
var homeTeam, awayTeam, gameResult, winner, loser, ot, standings;
_.each(games, function(game) {
homeTeam = teams[game.homeTeam-1];
awayTeam = teams[game.awayTeam-1];
gameResult = {};
winner = {};
loser = {}
ot = {};
standings = [];
ot.isOvertime = game.hadOT;
ot.isShootout = game.hadSO;
if( game.awayTeamScore > game.homeTeamScore ) {
winner.team = awayTeam;
winner.score = game.awayTeamScore;
loser.team = homeTeam;
loser.score = game.homeTeamScore;
} else if ( game.awayTeamScore < game.homeTeamScore ) {
winner.team = homeTeam;
winner.score = game.homeTeamScore;
loser.team = awayTeam;
loser.score = game.awayTeamScore;
}
// adds game to grid
calc.formattedResults(game, homeTeam.id, awayTeam.id, progressGrid)
// adds scores to team
calc.recordGameResults(winner, loser, ot)
// other stats
angular.forEach(teams, function (team, index) {
team.goalDifferential = team.goalsFor - team.goalsAgainst
team.gamesPlayed = team.wins + team.regulationLosses + team.overtimeShootoutLosses
team.regulationOvertimeWins = team.wins - team.shootoutWins
team.points = team.wins * 2 + team.overtimeShootoutLosses * 1 + team.regulationLosses * 0
});
})
},
recordGameResults: function(winner, loser, ot) {
if ( ot.isShootout || ot.isOvertime ) {
loser.team.overtimeShootoutLosses++
}
else {
loser.team.regulationLosses++
}
if ( ot.isShootout ) {
winner.team.shootoutWins++
loser.team.shootoutLosses++
}
winner.team.wins++
winner.team.goalsFor += winner.score
winner.team.goalsAgainst += loser.score
loser.team.goalsFor += loser.score
loser.team.goalsAgainst += winner.score
},
formattedResults: function(game, homeTeamID, awayTeamID, progressGrid) {
var formattedResult = game.awayTeamScore + "-" + game.homeTeamScore + " ";
formattedResult += game.hadSO ? '(SO)' : '' || game.hadOT ? '(OT)' : '';
progressGrid[homeTeamID - 1][awayTeamID - 1] = formattedResult;
return formattedResult
}
}
return calc;
})
.factory('ProgressGrid', function() {
var grid = {
init: function(numberOfTeams) {
var g = new Array(numberOfTeams)
for(var i = 0; i < numberOfTeams; i++) {
g[i] = new Array(numberOfTeams);
for(var j = 0; j < numberOfTeams; j++) {
g[i][j] = "";
}
}
return g;
}
}
return grid;
});
}());
锦标赛服务
(function(){
angular.module('n16', ['ui.router', 'Dashboard', 'Games', 'Teams', 'Players'])
.config(['$stateProvider', '$urlRouterProvider',function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('dashboard', {
url: '/',
templateUrl: '/app/dashboard/dashboard.html',
controller: 'dashboardController as ctrl'
})
.state('teams', {
url: '/teams',
templateUrl: '/app/teams/teams.html',
controller: 'teamsController as ctrl'
})
.state('games', {
url: '/games',
templateUrl: '/app/games/games.html',
controller: 'gamesController as ctrl'
})
.state('players', {
url: '/players',
templateUrl: '/app/players/players.html',
controller: 'playersController as ctrl'
});
}])
.controller('navigationController', function() {
var self = this;
self.navList = []
})
.service('TournamentService', ['$http','$q',function($http, $q) {
var getTournament = function() {
return $http.get('/tournaments/2016B', {cache: true }).then(function(tournament) {
return tournament.data[0]
})
}
var getGames = function() {
return $http.get('/games').then(function(games) {
return games.data
})
}
return $q.all([getTournament(), getGames()]).then(function(resultsArray) {
var tournament = resultsArray[0]
var games = resultsArray[1]
return {
tournament: tournament,
games: games,
teams: tournament.teams
}
});
}]);
})();
这是视图
<!-- Progress Grid -->
<h3 class="">Games Played: {{ ctrl.games.length }} of {{ctrl.totalGames}} <span class="text-muted">({{ ctrl.percentGamesPlayed | number : 0 }}%)</span></h3>
<div class="table-responsive">
<table class="table table-bordered" width="100%">
<tr>
<th ng-repeat="team in ctrl.teams">
{{team.teamName}}
</th>
<th> </th>
</tr>
<tr ng-repeat="teamAway in ctrl.teams">
<td ng-repeat="teamHome in ctrl.teams" ng-class="{bg: $index==$parent.$index}" width="177">
{{ ctrl.progressGrid[teamAway.id - 1][teamHome.id - 1] }}
<!-- <span class="text-danger">{{ teamAway.id - 1 }}, {{ teamHome.id - 1 }}</span> -->
</td>
<th>
@{{teamAway.teamName}}
</th>
</tr>
</table>
</div>
<!-- Team Standings -->
<h3>Standings</h3>
<div class="table-responsive">
<table class="table table-bordered" width="100%">
<thead>
<tr>
<th>Team Name</th>
<th>Players</th>
<th>GP</th>
<th>W</th>
<th>RL</th>
<th>OSL</th>
<th>PTS</th>
<th>SW</th>
<th>SL</th>
<th>ROW</th>
<th>GF</th>
<th>GA</th>
<th>GDIFF</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="team in ctrl.teams | orderBy: ['-points', 'gamesPlayed', '-regulationOvertimeWins','-goalDifferential']">
<td width="130">{{team.teamName}}</td>
<td>{{team.player1}}<br>{{team.player2}}</td>
<td class="statDetail">{{team.gamesPlayed}}</td>
<td class="statDetail">{{team.wins}}</td>
<td class="statDetail">{{team.regulationLosses}}</td>
<td class="statDetail">{{team.overtimeShootoutLosses}}</td>
<td class="statDetail">{{team.points}}</td>
<td class="statDetail">{{team.shootoutWins}}</td>
<td class="statDetail">{{team.shootoutLosses}}</td>
<td class="statDetail">{{team.regulationOvertimeWins}}</td>
<td class="statDetail">{{team.goalsFor}}</td>
<td class="statDetail">{{team.goalsAgainst}}</td>
<td class="statDetail">{{team.goalDifferential}}</td>
</tr>
</tbody>
</table>
</div>
<hr>
<h1>
Games
<button class="btn btn-primary btn-sm" ng-show="!ctrl.isEditing" ng-click="ctrl.showModal()">Add Game</button>
</h1>
<div class="table-responsive">
<table class="table">
<thead>
<th>Game #</th>
<th>Date</th>
<th>Final Score</th>
</thead>
<tbody>
<tr ng-repeat="game in ctrl.games | orderBy: '-id'">
<td>{{ game.id }}</td>
<td>{{ game.gameDate | date: medium }}</td>
<td>
<span ng-class="{ 'winner': game.awayTeamScore > game.homeTeamScore }">{{ ctrl.getTeamName(game.awayTeam) }}</span>
@
<span ng-class="{ 'winner': game.homeTeamScore > game.awayTeamScore }">{{ ctrl.getTeamName(game.homeTeam) }}</span>
<span>{{ game.awayTeamScore }} - {{game.homeTeamScore }}</span>
<span class="label label-warning" ng-show="game.hadOT && !game.hadSO">OT</span>
<span class="label label-danger" ng-show="game.hadSO">SO</span>
</td>
</tr>
<tr ng-show="ctrl.games.length < 1 "><td colspan="3">no games played at this time.</td></tr>
</tbody>
</table>
</div>
<div class="modal show" ng-show="ctrl.isEditing">
<div class="modal-dialog">
<form class="modal-content" name="ctrl.addGameForm" ng-submit="ctrl.addGame()">
<div class="modal-header">
<h2>Add Game</h2>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="form-group row">
<label for="date">Game Date</label>
<input type="date" class="form-control" name="gameDate" ng-model="ctrl.newGame.gameDate" required>
</div>
<div class="row">
<div class="col-sm-5 well">
<div class="form-group">
<label for="">Away Team</label>
<select name="awayTeam" class="form-control" ng-model="ctrl.newGame.awayTeam" required>
<option value=""></option>
<option ng-repeat="team in ctrl.teams" value="{{ team.id }}">{{ team.teamName }}</option>
</select>
</div>
<div class="form-group">
<label for="">Final Score</label>
<input type="number" name="awayTeamScore" class="form-control" ng-model="ctrl.newGame.awayTeamScore" required min="0"/>
</div>
</div>
<div class="col-sm-2 text-center">
@
</div>
<div class="col-sm-5 well">
<div class="form-group">
<label for="">Home Team</label>
<select name="homeTeam" class="form-control" ng-model="ctrl.newGame.homeTeam" required>
<option value=""></option>
<option ng-repeat="team in ctrl.teams" value="{{ team.id }}">{{ team.teamName }}</option>
</select>
</div>
<div class="form-group">
<label for="">Final Score</label>
<input type="number" name="homeTeamScore" class="form-control" ng-model="ctrl.newGame.homeTeamScore" required min="0" />
</div>
</div>
</div>
<div class="form-group">
<label class="checkbox">
<input type="checkbox" name="hadOT" ng-model="ctrl.newGame.hadOT" ng-click="ctrl.newGame.hadSO = false">
Overtime
</label>
<label class="checkbox">
<input type="checkbox" name="hadSO" ng-model="ctrl.newGame.hadSO" ng-click="ctrl.newGame.hadOT = false">
Shoot Out
</label>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-link" type="reset" data-dismiss="modal" ng-click="ctrl.hideModal()">Cancel</button>
<button class="btn btn-primary" type="submit" ng-disabled="(ctrl.newGame.homeTeam === ctrl.newGame.awayTeam) || (ctrl.newGame.homeTeamScore === ctrl.newGame.awayTeamScore) || ctrl.isSaving">Add Game</button>
</div>
</form>
</div>
</div>
答案 0 :(得分:0)
您的服务有两个目的:成为模特和API服务。因为您要返回这些API调用的结果,所以它会被缓存为TournamentService
的注入值。我建议你将这个逻辑分开。您的服务将更好地服务于此目的:
.service('TournamentService', ['$http','$q',function($http, $q) {
api = {
getTournament: function() {
return $http.get('/tournaments/2016B', {cache: true })
.then(function(tournament) { return tournament.data[0]})
}
getGames: function() {
return $http.get('/games')
.then(function(games){ return games.data })
}
}
return api
然后在您的控制器中,您可以使用$q.all
来呼叫服务,以汇总/按摩服务中的数据。
.controller('DashboardContoller', function(... TournamentService){
$q.all([TournamentService.getTournnament(), TournamentService.getGames()])
.then(function(rsps){
vm.tournament = rsps[0];
vm.games = rsps[1];
...
})
我倾向于以非常精细的方式考虑服务,以便您可以让控制器选择和选择他们如何请求数据的顺序。