Deepika Deepika - 2 months ago 8
AngularJS Question

Dynamic day and time field according to Number of lectures in AngularJs

I want to create dynamic fields (input :day and time) according to Number of lectures a tutor takes.

For e.g : If there is only one lecture per week, then a dropdown for a day input and two input type time will be created for timings from to like 2.00pm to 3:00 pm. For 2 lectures per week first day input then two time input followed by second day input and two time input.

I tried using jquery and its working but that was little complex by and using jquery with angular 'not a good idea.'

I Tried :

<fieldset style="display:none;" class="slot" >
<div ng-repeat="i in days | limitTo:-lectures">

<label>{{$index+1}}
<span>Select Day : </span>
<span>
<select ng-model="day" ng-options="x for x in days" ng-blur="sendTiming()"></select>
</span>
</label>

<label>Select Duration
<span >
<p id='datepair{{$index + 1}}' name='datepair{{$index + 1}}' class='datepair' data-language='javascript'>
<input type='text' class='time start' name='timefrom[{{$index + 1}}]' id='timefrom{{$index + 1}}' ng-model="fromtime[]" required ng-blur="sendTiming()" ng-value=""/> to
<input type='text' class='time end' id='timeto{{$index + 1}}' name='timeto[{{$index + 1}}]' ng-model="totime" required ng-blur="sendTiming()" ng-value=""/>
</p>
</span>
</label>
</div>
</fieldset>


Any idea is welcome.
Thanks

EDIT: here is a fiddle : https://jsfiddle.net/8btsqbnu/

Answer

plucker

It adds 1 input for day, 2 inputs for time for each button click.

you need to have a directive with isolated scope to dynamically add controls

.directive("lectureTimings", function(){
  return{
    restrict:'E',
    scope:{
      days : '=',
      timing: '='
    }, 
    templateUrl:'timings.html'
  }
})

Directive template

<select ng-model="timing.day" ng-options="x for x in days" ng-blur="sendTiming()"></select>
<br/>
<input ng-model="timing.from"/>to<input ng-model="timing.to"/>

Main controller template

 <input type="button" name="addmore" class="addmore" ng-click="addTiming();" value="Add Classes"/>

  <div ng-repeat= "timing in timingsData">
    <br/>
  <lecture-timings  timing="timing" days="days"></lecture-timings>
 </div>

each time user click button

We push new object to timingsData and ng-repeat will automatically repeat

$scope.addTiming = function(){

    $scope.timingsData.push({
     day:'',
     from: '',
     to: ''
   });
}
Comments