How to set up ngRepeat to generate entries stored

2019-06-10 00:58发布

问题:

I have table rows which I need to generate based on template. There should be some variables. For example persons[0].lastName should be persons[1].lastName for next row and so on. I want to store template in html file. I use angular-ui/ui-router. How to make this work?

Example:

<tr>
    <td>
        <div class="form-group first-name">
            <label>First name</label>
            <input type="text" ng-class="{'input-valid': isValidField('FirstName', persons[0].firstName)}" name="firstName" class="form-control input-name" ng-model="persons[0].firstName" ng-focus="focused('inputFirstName', 0)" placeholder="-">
        </div>

    </td>
    <td>
        <div class="form-group last-name">
            <label>Last name</label>
            <input type="text" ng-class="{'input-valid': isValidField('LastName', persons[0].lastName)}" name="lastName" class="form-control input-name" ng-model="persons[0].lastName" ng-focus="focused('inputLastName', 0)" placeholder="-">
        </div>

    </td>
</tr>

UPDATE

I find that ui router supports resolution of dependent objects and it's injection into controller. I successfully got html at string using resolve and $http inside of it. Now I need to replace 1 to relevant digit for each iteration. What is the best practice to do it?

UPDATE 2

I am not sure if ngRepeat is relevant here because I don't have list of objects to iterate. For example in imperative languages ngRepeat would equal foreach but I need just for loop where I can specify number of elements i need

UPDATE 3 I added all rows to array tableRowsHTML. Now I have troubles to render it in view as raw HTML. This simply does not work:

<table>
<tr> static stuff here </tr>
 <tr ng-repeat="el in tableRowsHTML track by $index">
                            {{el}}
</tr>
</table>

How to fix it?

回答1:

Use something like this

    <tr>
<td>
    <div class="form-group first-name" ng-repeat="name in firstNames track by $index">
        <label>First name</label>
        <input type="text" ng-class="{'input-valid': isValidField('FirstName', persons[$index].firstName)}" 
        name="firstName" class="form-control input-name" ng-model="persons[$index].firstName" 
        ng-focus="focused('inputFirstName', 0)" placeholder="-">
    </div>

</td>
<td>
    <div class="form-group last-name" ng-repeat="name in lastNames track by $index">
        <label>Last name</label>
        <input type="text" ng-class="{'input-valid': isValidField('LastName', persons[$index].lastName)}" 
        name="lastName" class="form-control input-name" ng-model="persons[$index].lastName" 
        ng-focus="focused('inputLastName', 0)" placeholder="-">
    </div>

</td>

here firstNames, and lastNames are the list of names.