Vignesh Vignesh - 1 month ago 12
Javascript Question

ng-repeat for tr to add rows dynamically.

<tr class="workTime" ng-repeat="worktime in doctor.shift" >
<td><select name="multipleSelect" class="form-control selectpicker"
id="multipleSelect" ng-model="doctor.shift.workDays" multiple>
<option ng-repeat="days in weekdays">{{days}}</option>
</select>
</td>
<td><input type="text" class="form-control" ng-model =
"doctor.shift.workFrom"></td>
<td><input type="text" class="form-control" ng-model =
"doctor.shift.workTo">
</td>
<td><span class="glyphicon **glyphicon-plus** glyph_size " ng-
click="addWorkTime()" aria-hidden="true "></span></td>
</tr>


I am new to Angular. I would like to repeat the tr on click of the glyphicon-plus. I am not sure how to do this. I am not fetching any data. I just want to add a row with the respective fields on click of the glyphicon-plus. Can some please help me to resolve this. And if I have to write any script. What script do I have to write

Answer

OK, here's the sort answer:

var app = angular.module('main', []); 
app.controller('ctrl', function ($scope) {
    // create an object to hold the collection
    $scope.doctor = {
        shift : {
        worktimes: []
      }
    };

    $scope.addWorkTime = function() {
        // add an element to the end of the array
      $scope.doctor.shift.worktimes.push( {
                workDay: 1,
            workFrom: '9:00',
            workTo: '22:00'
      });
    };
    // add an initial row - if there are no rows, there's no add button!
    $scope.addWorkTime();
});

https://jsfiddle.net/cglist/t661eh5y/5/?utm_source=website&utm_medium=embed&utm_campaign=t661eh5y

The long answer is that there's some funny stuff in your html that makes it clear you're just getting started with Angular. For starters, when you say this: ng-repeat="worktime in doctor.shift" ..."worktime" is a temporary variable created solely for iterating over the object or (more likely) collection. Therefore, in the repeated template, you'd want to bind to things like: "worktime.workFrom" You'll see that I tweaked your html and your data model to make it all work, while trying to guess at what you were trying to accomplish.

Next, for the options on your select box, the current way of doing it is with "ngOptions", and not "ngRepeat" : https://docs.angularjs.org/api/ng/directive/ngOptions

Comments