How to return the value of a select to an ng-repeat at the angle

Asked

Viewed 344 times

1

I have a select that has 3 options 1,2 and 4, I need to choose one of these numbers a repeat div 1, 2 or 4 times according to the chosen select, as I do with Angular?

1 answer

4


A very simple example would be to make a range of the numbers creating a filter for that purpose and in accordance with the choices made by select, change a variable of $scope to load the div, exemplo:

var app = angular.module('app', [])
app.filter('range', function() {
  return function(input, total) {
    total = parseInt(total);
    for (var i = 0; i < total; i++) {
      input.push(i);
    }
    return input;
  };
});
app.controller('ctrl', function($scope) {
  $scope.line = 0;
});
.divC {
  border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <select ng-model="line">
  <option value="0">Inicial</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="4">4</option>
</select>

  <div>
    <div class="divC" ng-repeat="n in [] | range:line">
      {{$index}}
    </div>
  </div>

</div>

Another way, creating a Array:

var app = angular.module('app', [])
app.controller('ctrl', function($scope) {
  $scope.line = 0;
  $scope.lines = function(value) {    
    return new Array(parseInt(value));       
  };  
});
.divC {
  border:1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!--Pessoal tenho um select que tem 3 opções 1,2 e 4, preciso que ao escolher um desses números uma div se repita 1, 2 ou 4 vezes de acordo com o select escolhido, como faço isso com Angular?-->
<div ng-app="app" ng-controller="ctrl">
  <select ng-model="line">
  <option value="0">Inicial</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="4">4</option>
</select>
<div>
    <div class="divC" ng-repeat="n in lines(line) track by $index">
      {{$index}}
    </div>
  </div>
</div>

References:

  • 1

    Cool brother, well that I needed, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.