AngularJS ng-repeat用于输入数组

时间:2017-06-23 13:56:37

标签: angularjs arrays angularjs-ng-repeat

我有汽车的空模型:

$scope.registration.cars = {
    1: {
        capacity: '',
        count: '',
        license: ''
    },
    2: {
        capacity: '',
        count: '',
        license: ''
    }
};

然后我使用ng-repeat来生成汽车形式:

<div class="row row_vehicles" ng-repeat="(key, value) in registration.cars">
    <input type="number" name="registration_car_capacity[{{key}}]" ng-model="registration.car[{{key}}].capacity" />
    <input type="number" name="registration_car_count[{{key}}]" ng-model="registration.car[{{key}}].count" required />
    <input type="text" name="registration_car_license[{{key}}]" ng-model="registration.car[1].license" ng-minlength="7" required />
</div>

但这不起作用。如何将KEY插入ng-model数组?

2 个答案:

答案 0 :(得分:2)

您只需删除包含密钥的插值{{}}即可。你不能在角度指令中使用它。

<div ng-controller="MyCtrl">
    <div class="row row_vehicles" ng-repeat="(key, value) in registration.cars">
        <input type="number" name="registration_car_capacity[key]"
        ng-model="registration.cars[key].capacity"
        />
        <input type="number" name="registration_car_count[key]"
        ng-model="registration.cars[key].count"
        required />
        <input type="text" name="registration_car_license[key]"
        ng-model="registration.cars[key].license"
        ng-minlength="7" required /> 
    </div>
</div>

工作小提琴http://jsfiddle.net/ADukg/12094/

答案 1 :(得分:1)

不要在角度范围内使用插值运算符({{..}})。(类似于ng-*),在您的情况下ng-model

<div class="row row_vehicles" ng-repeat="(key, value) in registration.cars">
    <input type="number" name="registration_car_capacity[key]" ng-model="registration.car[key].capacity" />
    <input type="number" name="registration_car_count[key]" ng-model="registration.car[key].count" required />
    <input type="text" name="registration_car_license[key]" ng-model="registration.car[key].license" ng-minlength="7" required />
</div>