重复选择ng-repeat Angularjs中的选项

时间:2015-10-19 11:29:53

标签: javascript angularjs

我有一个在ng-repeat中重复选择选项的表单。在这种形式中,我想为select元素选择defualt值。实际上,在第一个选择元素中,所选择的值是“n1”,而在第二个选择元素中,所选择的值是“n2”。而在牵引中,选择元素defualt值为“n2”。 我的问题是什么?

function MyCntrl($scope) {
    $scope.data = {
        orders: [{ s:'' }]
    };

    $scope.list = [1,2];
    $scope.data.orders[0] = "n1";
    $scope.data.orders[1] = "n2";
    $scope.sizes = [ {code: 1, name: 'n1'}, {code: 2, name: 'n2'}];
    $scope.update = function() {
        console.log($scope.item.code, $scope.item.name)
    }
}
<!doctype html>
<html ng-app>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
    <div ng-controller="MyCntrl">
        <div ng-repeat="l in list track by $index">
            <select ng-model="data.orders[$index]" ng-change="update()">
                <option ng-selected ="data.orders[$index] == size.name" ng-repeat="size in sizes">
                    {{size.name}}
                </option>
            </select>
        </div>
        <select ng-model="data.orders[0]" ng-change="update()">
            <option ng-selected ="data.orders[0] == size.name" ng-repeat="size in sizes">
                {{size.name}}
            </option>
        </select>
        <select ng-model="data.orders[1]" ng-change="update()">
            <option ng-selected ="data.orders[1] == size.name" ng-repeat="size in sizes">
                {{size.name}}
            </option>
        </select>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

请尝试使用此代码。它使用$parent.$index代替$index

ng-repeat默认按$index跟踪,因此无需指定。

这会导致内循环出现问题,也会导致$index跟踪。当你在内部循环中说$ index时,它会获取内部循环索引,该索引总是会被评估为真。

&#13;
&#13;
function MyCntrl($scope) {
    $scope.data = {
        orders:[{ s:'' }]
    };
    $scope.list = [1,2];
    $scope.data.orders[0] = "n1";
    $scope.data.orders[1] = "n2";
    $scope.sizes = [{code: 1, name: 'n1'}, {code: 2, name: 'n2'}];
    $scope.update = function() {
        console.log($scope.item.code, $scope.item.name)
    }
}
&#13;
<!doctype html>
<html ng-app>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
    <div ng-controller="MyCntrl">
        <div ng-repeat="l in list track by $index">
            <select ng-model="data.orders[$index]" ng-change="update()">
                <option ng-selected ="data.orders[$parent.$index] == size.name" ng-repeat="size in sizes">
                    {{size.name}}
                </option>
            </select>
        </div>
    </div>
</body>
</html>
&#13;
&#13;
&#13;

相关问题