Angular-JS模板可以是通用的吗?

时间:2015-02-03 05:00:31

标签: angularjs

我有以下html模板以及从服务器检索的JSON格式。这已经适用于冰箱。我可以轻松地复制和粘贴模板,更改变量名称并使其适用于其他设备类型。但是,我不想违反DRY原则。是否可以在不重复模板的情况下完成这项工作?使用ng-include可能吗? (顺便说一句,我是AngularJS的初学者)

<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: ''}]
};

1 个答案:

答案 0 :(得分:1)

使用ng-include是个不错的选择。对于模板中的变量,您不一定要更改其名称,而是可以使用ng-init来执行此操作:

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