重用HTML但绑定不同的模型

时间:2014-09-20 09:23:11

标签: javascript angularjs angular-ngmodel

我在我的网站上使用AngularJS。我网站上的一个页面非常大,因为它有很多HTML元素。想象一下这样的事情:

<div id="bronze">
  <input ng-model="league.bronze.name">
  <input ng-model="league.bronze.title">
  <input ng-model="league.bronze.description">
  ... about 15 more inputs ...
  <input ng-model="league.bronze.color1">
  <input ng-model="league.bronze.color2">
</div>
<div id="silver">
  <input ng-model="league.silver.name">
  <input ng-model="league.silver.title">
  <input ng-model="league.silver.description">
  ... about 15 more inputs ...
  <input ng-model="league.silver.color1">
  <input ng-model="league.silver.color2">
</div>

我还有goldplatinum。网站管理员必须填写所有这些设置。这对他来说不是问题。但对我来说,这是一个开发人员。

每次我将一个或多个元素添加到“bronze”部分时,我也必须对其他每个部分执行相同的操作。唯一的区别是ng-model值。

难道没有更聪明的方法吗?因为现在每次需要添加一个元素时我都会重复自我...

2 个答案:

答案 0 :(得分:0)

查看使用ng-repeat作为输入字段的快速示例

plunker

在你的情况下,它将是:

<div ng-repeat="league in leagues>
        <input ng-model="league.bronze.name">
  <input ng-model="league.title">
  <input ng-model="league.description">
  ... about 15 more inputs ...
  <input ng-model="league.color1">
  <input ng-model="league.color2">
</div>

答案 1 :(得分:0)

在您的控制器中执行:

$scope.types = ['gold', 'silver', 'bronze'];
$scope.properties = ['name', 'title', 'description'];

在你的HTML中执行此操作:

<div ng-repeat="myType in types" id="{{myType}}">
  <input ng-repeat="myProperty in properties" ng-model="league[myType][myProperty]">
</div>

EXAMPLE

相关问题