João Serra
João Serra

Reputation: 253

How can i do an ng-repeat by a given select option value

So my problem is as follows, i have this HTML

        <div class="col-sm-4">
            <p><span>Teste A/B:</span></p>
            <label class="label-radio">
                <input type="radio" class="radio" name="ab-test" value="true" ng-model="isTestAvailable"> Sim </label>
            <label class="label-radio">
                <input type="radio" class="radio" name="ab-test" value="false" ng-model="isTestAvailable"> Não </label>
        </div>
        <div class="col-sm-4">
            <p><span>Nº de testes:</span></p>
            <select class="form-control" ng-model="tests.number">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </select>
        </div>
    </div>

What i'm trying to do is make it so that when the user changes the select to another value i generate the given amount of test inputs via ng-repeat

    <div ng-if="isTestAvailable == 'true'" ng-repeat="test in tests">
        <hr>
        <div class="row">
            <div class="col-sm-12">
                <h3>Test {{$index}}</h3>
                <p><span>Specifications:</span></p>
                <textarea id="teste1" class="form-control" onkeyup="resizeTextarea('test1')" data-resizable="true"></textarea>
            </div>
        </div>
        <hr>
    </div>

My controller contains this $watch

$scope.$watch("tests.number", function(newVal, oldVal) {
    $scope.tests = [{}];
    var i = parseInt(newVal);
    for(var x = i; x <= newVal; x++) {
        $scope.tests.push({});
    }
});

that i tried to use in order to change the amount of test objects when the value changes, i tried using a simple variable as well and doing ng-repeat("i in tests.number") instead but that didn't work, what can i do so that the ng-repeat works with my given select option value?

Upvotes: 0

Views: 38

Answers (1)

Silvinus
Silvinus

Reputation: 1445

I suggest to you, to use another variable instead of tests.number because you override it in your watcher. Please check this plunker : https://plnkr.co/edit/XnV9MKjIYe1YOL4hR6Le?p=preview I use another variable and bind ng-change instead of watch

<select class="form-control" ng-model="testNumber" ng-change="changeTestNumber()">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Upvotes: 1

Related Questions