TWLATL
TWLATL

Reputation: 2879

Form validity using Angular ng-repeat

I have an Angular form that is parsing some JSON data.
I'm rendering using ng-repeat. However, I'm having an issue in that the form never becomes valid when a radio button in each group is selected.

I suspect the issue lies with the ng-model in each input, but I can't seem to figure out the correct way to dynamically create an ng-model inside an ng-repeat.

Form block code:

<form name="posttestForm">
  <alert ng-repeat="alert in alerts" 
         type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</alert>
  <div class="well question-well" ng-repeat="question in questions">
    <p>
      <strong>{{question.question}}</strong>
    </p>
    <ul>
      <li ng-repeat="answers in question.answers">
        <input ng-model="Q[question.id]" 
               type="radio" name="Q{{question.id}}" value="{{answers.id}}" 
               required="" data-key="{{answers.isCorrect}}" />{{answers.answer}}
      </li>
    </ul>
  </div>
  <button type="submit" class="btn btn-primary" ng-click="EvaluatePosttest(3)" 
          ng-show="!TestPassed">
    Submit Questions</button>
</form>

Here's a Plunkr that shows the dynamic code and demonstrates the form never turning valid when a radio button in each group is selected.

http://plnkr.co/edit/HQGPIOCdn3TGlE96CpK5?p=preview

And here's a Plunkr using static content displaying it working.

http://plnkr.co/edit/ZFt2VnBfaQjuu73kaNQJ?p=preview

Upvotes: 0

Views: 69

Answers (2)

Italo Ayres
Italo Ayres

Reputation: 2663

You can do a custom form validation inside your controller. In your case:

$scope.Q = [];
$scope.$watch('Q', function (Q) {
    $scope.posttestForm.$setValidity('count', Q.length >= $scope.questions.length);
}, true);

Inside that, you can do whatever validation you want.

Here's the working plunkr: http://plnkr.co/edit/7Ww4fjJzkDjifPaZ2QtG?p=preview

Upvotes: 0

Walfrat
Walfrat

Reputation: 5353

Just add this in your javascript controller

$scope.Q = [undefined,undefined,undefined,undefined,undefined,undefined];

Explanation : you set ng-model as Q[question.id] but Q is undefined so the ng-model won't ever work. You always must initialize variable in the controller. The only case it works not initialize is when you do : ng-model="test"

if you do

ng-model="test.test"
ng-model="test[0]"

It won't ever work if it's not initialized properly.

Upvotes: 1

Related Questions