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

时间:2022-12-03 14:28:30

I have a following collection of fields.

我有以下字段集合。

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

I need to have input controls dynamically generated as many as the fields above. So a fixed version of below

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

<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>

would hopefully generate something like below...

希望产生类似下面的东西......

<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>

Any ideas? Thanks!

有任何想法吗?谢谢!

1 个解决方案

#1


You need to use bracket notation to access variable object property:

您需要使用括号表示法来访问变量对象属性:

<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>

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

#1


You need to use bracket notation to access variable object property:

您需要使用括号表示法来访问变量对象属性:

<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>

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