AngularJS中的动态ng模型绑定ng-repeat循环

时间:2015-05-08 21:26:38

标签: javascript angularjs

我有以下字段集合。

$scope.fields = ['name','postcode','phone'];

我需要动态生成输入控件,与上面的字段一样多。所以下面的固定版本

<div class="col-sm-3" ng-repeat="user in users">
    <div ng-repeat="field in fields">
        <input class="form-control" ng-model="user.field" /> <!-- .field isn't resolving -->
    </div>
</div>
希望能产生类似下面的东西......

<div class="col-sm-3" ng-repeat="user in users">
    <div><input class="form-control" ng-model="user.name" /></div>
    <div><input class="form-control" ng-model="user.postcode" /></div>
    <div><input class="form-control" ng-model="user.phone" /></div>
</div>

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:6)

您需要使用bracket notation来访问变量对象属性:

<div class="col-sm-3" ng-repeat="user in users">
    <div ng-repeat="field in fields">
        <input class="form-control" ng-model="user[field]" />
    </div>
</div>

演示: http://plnkr.co/edit/fkCYr4k0RwizxsOS9HhC?p=preview