使用angularjs更新操作

时间:2016-03-21 20:31:39

标签: angularjs node.js mongoose

我试图更新包含多个数组的json集合。我试图使用$ resource服务与数据进行交互。

我添加了一个带有PUT方法的更新选项,但它在下面抛出了异常

错误:vm.updatetour。$ update不是函数。

我已经把它放到一个非工作的plunker中,并且json数据也是http://plnkr.co/edit/5wtf0BHThg7rORJDYleX?p=catalogue

感谢任何帮助

//// this is the controller

(function() {
  angular.module('Admin', ['ui.router', 'ngResource', 'Services'])
 .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {

$urlRouterProvider.otherwise('/');

$stateProvider
  .state('admin', {
    url: '/',
    templateUrl: '/app/admin/admin.html',
    controller: 'AdminController as vm'
  })
  .state('admin.tournaments', {
    url: 'tournaments',
    templateUrl: '/app/admin/tournament.html',
    controller: 'AdminController as vm'
  })
  .state('admin.users', {
    url: 'users',
    templateUrl: '/app/admin/users.html',
    controller: 'AdminController as vm'
  })
  .state('admin.createTournament', {
    url: 'create',
    templateUrl: '/app/admin/newTournament.html',
    controller: 'AdminController as vm'
  })
  .state('admin.teams', {
    url: 'teams',
    templateUrl: '/app/admin/teams.html',
    controller: 'AdminController as vm'
  })

  }])

.controller('AdminController', AdminController);

AdminController.$inject = ['TournamentService','UserService','TeamService', '$q', '$location','$scope','$filter','$http','$stateParams','$resource'];
function AdminController(TournamentService, UserService, TeamService, $q, $location, $scope, $filter, $http, $stateParams, $resource) {
var vm = this;
var tournaments = TournamentService.query();
var users = UserService.query();
var teams = TeamService.query()
vm.availablePlayers = [];
vm.newTournament = {};
vm.newTournament.teams = [];
vm.isSavingTournament = false;

$q.all([tournaments, users, teams]).then(function(results) {
  vm.users = users;
  vm.availablePlayers = users;
  vm.tournaments = tournaments;
  vm.teams = teams;
  console.log(vm.tournaments)
})

vm.showTournament = function() {
  var tournament = TournamentService.query({id: vm.selectedTournamentId}, function() {
    vm.selectedTournament = tournament[0]
  });
}

var Tourn = $resource('/api/tournaments/:id', {id: '@_id'}, {
  update: {method: 'PUT'},
  query: {method: 'GET', isArray: true}
})


vm.showUpdateTournament = function(form) {

  var updatetour = Tourn.query( { id: vm.selectedTournamentId});
  vm.updatetour = vm.tourTeams;
  vm.updatetour.$update();
    console.log(vm.tourTeams)
};

//// set these checkboxes default value to false and hipchatroom to empty value if it's not specified.
   vm.newTournament.hide = false
   vm.newTournament.playoffs = false
   vm.newTournament.hipchatroom = '';
   vm.newTournament.hipchatkey = '';

   vm.addNewTournament = function(formValid) {
    //console.log(vm.newTournament)
     if(formValid){
      TournamentService.save(vm.newTournament)
       alert('Tournament Saved');
       location.reload();
     }
   }



}

}());


<form novalidate ng-submit="vm.showUpdateTournament(vm.tournamentEdit)" method="post" name="vm.tournamentEdit" ng-show="vm.selectedTournament" ng-model="vm.selectedTournament" >

  <h1>{{vm.selectedTournament.name}}</h1>

  <div class="row">
      <div class="form-group col-sm-6">
      <label>Hipchat Room</label>
      <input type="text" class="form-control" ng-model="vm.selectedTournament.hipchatroom">
      </div>
    <div class="form-group col-sm-6">
      <label>Hipchat Key</label>
      <input type="text" class="form-control" ng-model="vm.selectedTournament.hipchatkey">
    </div>
  </div>
  <br>
  <div class="form-group">
    <span style="padding:5px">
      <label for="">Hide Tournament</label>
      <input type="checkbox" ng-model="vm.selectedTournament.hide">
    </span>
     | 
      <span style="padding:5px">
        <label for="">Start Playoffs</label>
        <input type="checkbox" ng-model="vm.selectedTournament.playoffs">
      </span>
   </div>


  <h2>Teams</h2>
  <div class="table-responsive">
    <table class="table table-bordered" width="100%">
      <thead>
        <tr>

          <th>Team Name</th>
          <th>Players</th>
          <th>
            ST
          </th>
          <th>
            PWR
          </th>

        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="teamz in vm.selectedTournament.teams">

          <td width="130" style="vertical-align:middle">



            <select name="team" class="form-control" ng-options="team.name for team in vm.teams track by team.teamid " ng-model="vm.tourTeams[$index]" ng-disabled="vm.selectedTournament.games.length > 0 || vm.selectedTournament.playoffGames.length > 0 " required >
              <option value=""></option>
               <!-- <input text name="team"  ng-model="vm.tourTeams[$index].name"> -->
          </td>
          <td><!-- {{ vm.getPlayerName(team.player1).local.fullname }}<br>{{vm.getPlayerName(team.player2).local.fullname}} -->


            <table width="30%">
              <tr>
                <td style="padding-bottom:10px">
                  <select name="user1" class="form-control" ng-options="user.local.fullname for user in vm.users track by user._id " ng-model="vm.tourPlayer1[$index]" required>
                    <option value=""></option>
                <td>
              </tr>
              <tr>
                <td>
                  <select name="user2" class="form-control" ng-options="user.local.fullname for user in vm.users track by user._id " ng-model="vm.tourPlayer2[$index]" required>
                    <option value=""></option>
                </td>
              </tr>

           </table>
          </td>
          <td class="statDetail">{{team.strength}}</td>
          <td class="statDetail">{{team.PWR}}</td>

        </tr>
      </tbody>
    </table>
  </div>

  <h2>Games</h2>
  <div class="table-responsive">
    <table class="table table-striped">
      <thead>
        <th>Game #</th>
        <th>Date</th>
        <th>Final Score</th>
      </thead>
      <tbody>
        <tr ng-repeat="game in vm.selectedTournament.games | orderBy: '-id'">
          <td>{{ game.id }}</td>
          <td>{{ game.gameDate | date: medium }}</td>
          <td>
            <span ng-class="{ 'winner': game.awayTeamScore > game.homeTeamScore }">{{  game.awayTeam.name }}({{ game.awayTeamScore }})</span>
            @
            <span ng-class="{ 'winner': game.homeTeamScore > game.awayTeamScore }">{{ game.homeTeam.name }} ({{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="vm.selectedTournament.games.length < 1 "><td colspan="3">no games played at this time.</td></tr>
      </tbody>
    </table>
  </div>
  <h2>Playoffs</h2>
  <div class="table-responsive">
    <table class="table table-striped">
      <thead>
        <th>Game #</th>
        <th>Date</th>
        <th>Final Score</th>
      </thead>
      <tbody>
        <tr ng-repeat="playoffgame in vm.selectedTournament.playoffGames | orderBy: '-id'">
          <td>{{ playoffgame.id }}</td>
          <td>{{ playoffgame.gameDate | date: medium }}</td>
          <td>
            <span ng-class="{ 'winner': playoffgame.awayTeamScore > playoffgame.homeTeamScore }">{{  playoffgame.awayTeam.name }}({{ playoffgame.awayTeamScore }})</span>
            @
            <span ng-class="{ 'winner': playoffgame.homeTeamScore > playoffgame.awayTeamScore }">{{ playoffgame.homeTeam.name }} ({{playoffgame.homeTeamScore}})</span>
            <span class="label label-warning" ng-show="playoffgame.hadOT && !playoffgame.hadSO">OT</span>
            <span class="label label-danger" ng-show="playoffgame.hadSO">SO</span>

          </td>
        </tr>
        <tr ng-show="vm.selectedTournament.playoffGames.length < 1 "><td colspan="3">no games played at this time.</td></tr>
      </tbody>
    </table>
  </div>
<button class="btn btn-primary" type="submit">Update</button>
</form>

2 个答案:

答案 0 :(得分:0)

vm.updatetour变量没有$ resource对象引用。理想情况下,您应该对update对象进行TournamentService操作。

vm.showUpdateTournament = function(form) {
   var updatetour = Tourn.query( { id: vm.selectedTournamentId});
   vm.updatetour = vm.tourTeams;
   TournamentService.update(vm.updatetour).$promise.then(function(){
       console.log("Updation completed")
   });
};

答案 1 :(得分:0)

在代码中添加方法

vm.updatetour=function(form) {
      alert("Update has been called");
      // update your record here by calling the web API
    };