Ahmed A. Supzero Ahmed A. Supzero - 2 days ago 4
AngularJS Question

can't reset form input using ng-click

I want to reset input value using ng-click to add it's value to a $scope var then reset the input value

here is my html

<form ng-controller="questionsCTRL" class="ui large form" name="questionForm" ng-submit="addSurvey(questionForm)" novalidate>

<div class="ui segment" id="quest-answers">


<div class="two fields">
<div class="field">
<label>Add New Answer</label>
<div class="ui action input">
<input type="text" required name="answers" ng-model="answers"
ng-required="true" ng-minlength="5" placeholder="answer...">
<button type="button"
ng-click="addAnswer(questionForm.answers.$viewValue)"
ng-disabled="questionForm.answers.$invalid"
class="ui teal right labeled icon button">
<i class="add icon"></i>
Add
</button>
</div>
<small ng-show="questionForm.answers.$invalid" class="ui meta teal">Answers is required</small>
</div>
</div>
<div class="ui grid">
<div class="row">
<div class="eleven wide column">

<div class="field">
<div class="ui attached segment" ng-repeat="answer in answerGroup">
{{answer.text}}
<a href class="ui right floated link"><i class="circular delete icon"></i></a>
</div>
</div>

</div>
</div>
</div>
</div>
</form>


and this is controller content

UIASSIGN1.controller('questionsCTRL', function($scope , $rootScope , $state, $stateParams , $http ) {
// #dummy controller
$rootScope.sectorName = 'Questions';
var _SID = $stateParams.id;
$scope.answerGroup = [];

$http.get("api/survey/survey.json")
.then(function(response) {
var surveyArray = response.data;
$scope.surveyArray = [];
for (var i = 0; i < surveyArray.length; i++) {
var thisItem = surveyArray[i];
var thisElm = {name:thisItem.name,value:parseInt(thisItem._id)};
$scope.surveyArray.push(thisElm)
}

});

$scope.addAnswer = function(answer){
var inArray = {
text : answer
};
$scope.answerGroup.push(inArray);
$scope.questionForm.answers = {};
}
});


this ng-click adds value to $scope.userGroups but it doesn't reset the form input value only resets the $scope.questionForm.answers value to {}

Answer

You could do it like this. Define the answer on the scope

$scope.theAnswer = '';

Set this as your ngModel for the input field:

ng-model="theAnswer"

Simplify your ng-click like this and add the answer to the array directly in the controller and then cleanup the answer:

ng-click="addAnswer()"

$scope.addAnswer = function(){
      var inArray = {
        text : $scope.theAnswer
      };
      $scope.answerGroup.push(inArray);
      $scope.theAnswer = '';
  }
Comments