AngularJS:如何将ng-model绑定到ng-repeat内的数组

时间:2014-08-25 21:26:35

标签: angularjs angularjs-ng-repeat angularjs-ng-model

我似乎无法使我的多个下拉列表工作。

<div ng-repeat="i in [0,1,2,3,4] track by $index">
    <select ng-model="myArray[i]" ng-options="someList"></select>
</div>

在html中,结果是... ng-model =“myArray [i]而不是ng-model =”myArray [0]等。

我尝试过大括号,但不起作用。最接近的是ng-model =“myArray ['{{i}}'],但那不是我想要的。

编辑:这是一个小提琴来说明。

http://jsfiddle.net/dpkzzyug/1/

您需要检查HTML以查看结果字面上写出i(或在这种情况下为$ index)而不是值。

2 个答案:

答案 0 :(得分:2)

您所使用的代码,但问题是myArrayng-repeat范围的本地代码。您需要确保myArray存在于此范围之外。

以下内容将起作用:

<div ng-app ng-init="someList=[1,2,3]; myArray = []">
    <div ng-repeat="i in [0,1,2,3,4] track by $index">
        <select ng-model="myArray[i]" ng-options="i for i in someList"></select>

http://jsfiddle.net/778x0pm0/1/

我个人更喜欢使用controller as语法,因为这样可以更清楚一点:

<div ng-app=app ng-init="someList=[1,2,3]">
    <div ng-controller="ctrl as ctrl">
        <div ng-repeat="i in [0,1,2,3,4] track by $index">
            <select ng-model="ctrl.myArray[i]" ng-options="i for i in someList"></select>

http://jsfiddle.net/778x0pm0/

答案 1 :(得分:0)

我刚刚意识到html会写出i / $ index,即使angular的逻辑仍然有用。我在其他地方遇到了问题,并认为是因为这个原因。

相关问题