I'm learning AngularJS and I making simple task management application. Application is connecting to external rest service. I try to render all my tasks in activities (task's container) with add task button but when form is in loop then it's not sending anything.
Here's my html code:
<div id="task-group" ng-repeat="activity in activities | filter:query">
<p>
<h2>{{activity.activityName}}</h2></p>
{{activity.activityId}}
<form name="form" ng-submit="addTask()">
<input type="text" ng-model="sendTaskName">
<input type="hidden" name="{{activity.activityId}}" >
<input type="submit" class="btn-primary" value="Add task">
</form>
<ul class="task-list">
<li ng-repeat="task in activity.tasks">
<p>{{task.taskName}}</p>
</li>
</ul>
</div>
Add task function in my controller:
$scope.addTask = function(){
$http({
method: 'POST',
url: 'http://localhost:8080/add-task',
data: {taskName: $scope.sendTaskName, activityId: $scope.sendActivityId}
}).success(function(){
getActivities()
$scope.sendTaskName = ''
})
}
EDIT: @Mickael helps me to solve my problem. The solution is in his answer. Thank you very much once again ! ;)
You are using ng-repeat
and inside each iteration, you bind your inputs with the ng-model
directive.
What happens here is that on each iteration, a new scope is created. When you start typing inside your input, the sendTaskName
variable is created inside the scope of the iteration, not the scope of your controller.
When your form is submitted, you submit the variable of the scope of your controller, that's why you do not send anything.
To solve your problem, I suggest that you give parameters to your addTask
method:
<div id="task-group" ng-repeat="activity in activities | filter:query">
<p>
<h2>{{activity.activityName}}</h2></p>
{{activity.activityId}}
<form name="form" ng-submit="addTask(activity.activityId, sendTaskName); sendTaskName = '';">
<input type="text" ng-model="sendTaskName">
<input type="submit" class="btn-primary" value="Add task">
</form>
<ul class="task-list">
<li ng-repeat="task in activity.tasks">
<p>{{task.taskName}}</p>
</li>
</ul>
</div>
And use these parameters in your controller:
$scope.addTask = function(activityId, taskName) {
$http({
method: 'POST',
url: 'http://localhost:8080/add-task',
data: {taskName: taskName, activityId: activityId}
}).success(function(){
getActivities();
})
}
Next time, with a plunkr, I will be able to fix your code ;)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments