led
led

Reputation: 633

Angular-JS templates can be generic?

I have the following html template and the format of the JSON that I retrieve from the server. This already works fine for refrigerators. I can easily copy&paste the template, alter the variable names and make it work for other appliances types. However, I do not want to violate DRY principle. Is it possible to make this work without duplicating the template? Use ng-include maybe? (I am a beginner on AngularJS by the way)

<section>
<h4>Refrigerators</h4>
<span class="glyphicon glyphicon-plus-sign"></span>
<a href="#"
   ng-click="addNewAppliance(appliances.refrigerators)">Add a refrigerator</a>

<table class="table table-striped">
    <tr>
        <th>Refrigerator Name</th>
        <th>Purchase Date</th>
    </tr>
    <tr ng-repeat="refrigerator in appliances.refrigerators track by $index">
        <td>
            <input type="text"
                   required=""
                   placeholder="Name"
                   ng-model="refrigerator.name"/>
        </td>
        <td>
            <input type="number"
                   required=""
                   placeholder="Purchase Date"
                   ng-model="refrigerator.purchaseDate"/>
        </td>
    </tr>
</table>
</section>

$scope.appliances = {
    refrigerators: [{name: '', purchaseDate: ''}],
    dryers: [{name: '', purchaseDate: ''}],
    freezers: [{name: '', purchaseDate: ''}]
};

Upvotes: 0

Views: 108

Answers (1)

Rebornix
Rebornix

Reputation: 5270

Using ng-include is a good option. For variables in the tempalte, you don't necessarily have to alter their names, instead you can use ng-init to do the trick:

<div ng-init="appliances = appliancesFromOutterScope" ng-include="template.url"></div>

Upvotes: 1

Related Questions