laks laks - 4 months ago 6
HTML Question

AngularJS repeat HTML content based on Dropdown selection number

I have drop down to select a number.
Based on the selected value I need to repeat the sections in html.
For example if I choose 3 in the drop down then the page should display

Display section 1 of 3
Display section 2 of 3
Display section 3 of 3


Please help to figure out how I can achieve this. Your time and help is greatly appreciated.

Java Script:

angular.module("myApp", [])
.controller("SolutionCtrl", function SolutionCtrl() {
var vm = this;
vm.noOfSites = 0;
vm.updateSites = function() {
console.log(vm.noOfSites);
}
vm.getTimes = function(n) {
return new Array(n);
}
})


html:

<body>
<div ng-app="myApp">
<div ng-controller="SolutionCtrl as ctrl">
<div>
<h5>Select No of Sites:</h5>
<select ng-model="ctrl.noOfSites" ng-change="ctrl.updateSites()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div ng-repeat = "t in ctrl.getTimes(ctrl.noOfSites) track by $index">
<h2>Display section {{t}} of 3 </h2>
</div>
</div>
</div>

</body>


JSFiddle:

Answer

Working Fiddle: https://jsfiddle.net/mnaxp5nz/6/

HTML

<body>
  <div ng-app="myApp" ng-controller="myCtrl">
    <div>
      <div>
        <h5>Select No of Sites:</h5>
        <select ng-model = "noOfSites" ng-init = "noOfSites = 0" ng-change = "updateSections();">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
        </select>
      </div>
      <div ng-repeat = "section in sections">
        Section {{ $index + 1 }} of {{ sections.length }}
      </div>
    </div>

  </div>
</body>

Script

<script>

  var app = angular.module('myApp', []);

  app.controller('myCtrl', function($scope) {

    $scope.sections = [];

    $scope.updateSections = function () {

      $scope.sections = [];

      for (counter = 1; counter <= $scope.noOfSites; counter++) {

        $scope.sections.push(counter);

      }

    }

  });  

</script>
Comments