Mocktheduck Mocktheduck - 2 months ago 7
AngularJS Question

Angular it taking the old parameter when clicking button

I am trying to add a button which when clicked, calls a function which takes a parameter and sends it to my server. So far it looks like this:

<table class="table table-hover">
<thead>
<tr>
<th>Id</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="interview in $ctrl.pendingInterviews">
<td>{{ interview.id }}</td>
<td><a href="/#!/pending-interviews-list?interviewId={{interview.id}}"><input type="submit" name="Submit" id="submit" ng-click="$ctrl.addParticipant();"></a></td>
</tr>
</tbody>
</table>


What I have in my angular component:

var participant={
username:"mama",
interviewId:$routeParams.interviewId
};
console.log(participant);
console.log(JSON.stringify(participant));

this.addParticipant = function saveParticipant() {
console.log("in partikip")
Interview.addParticipant(JSON.stringify(participant))
.then(
function (errResponse) {
console.error('Error while fetching pending interviews');
}
);
}


And what I have in my angular service:

function addParticipant(participant) {
console.log("Im here too");
console.log(participant + "asdasdsda");
var deferred = $q.defer();
$http.post('http://localhost:8080/interviewsupdateparticipant', participant)
.then(
function (response) {
deferred.resolve(response.data);
},
function (errResponse) {
console.error('Error while adding participant');
console.error(''+ participant.username + participant.interviewId)
deferred.reject(errResponse);
}
);
return deferred.promise;
}


The problem is that first when I go to my page, participant from the controller has the username set to mama and the interviewId set to undefined. When I click the submit button, instead of sending the id and the hardcoded username, it sends undefined and the hardcoded username. Why? Why doesn't it automatically get the interviewId?

The moment I click Submit, the id stays undefined for some reason and it only changes if I click again. Any ideas what the problem could be?

Answer

Many things that could solve this:

  • Try using ngHref instead of just href when you have variable part of your url
  • Try passing the interview.id as a parameter to your addParticipant() method instead of getting it via the $routeParams variable
  • You have an input type="submit" outside any form, and inside an <a> link, try changing that
Comments