2

I am trying to use ng-options to return the index of an element in an array instead of its value:

the select directive:

<select ng-model="obj.value" ng-options="v for v in obj.values"></select> 

which is working fine if the datas are formatted like so:

{ "value": "value 3", "values": [ "value 1", "value 2", "value 3", "value 4"] } 

The problem is the web-service send datas like this:

{ "value": 2, "values": [ "value 1", "value 2", "value 3", "value 4"] }

Is it possible to modify the directive to :

  • by default, select the element which index correspond to value
  • when the user select an element, return its index (instead of its value)

?

4

1 回答 1

1

几乎已经完成了您需要的操作,但仍然存在一个问题:

JS:

var demo = angular.module("demo", []);

demo.controller("DemoController", ['$scope', function($scope){
    $scope.obj = {
        "value": 2,
        "values": [
            "value 1",
            "value 2",
            "value 3",
            "value 4"
        ]
    };
}]);

HTML:

<body data-ng-app="demo">
    <div data-ng-controller="DemoController">
        <select data-ng-model="obj.value">
            <option data-ng-repeat="i in obj.values"
                    value="{{$index}}"
                    data-ng-selected="$index == obj.value">
                        {{i}}
            </option>
        </select>
        {{obj}}
    </div>
</body>

但是obj.value在下拉列表中选择某些内容后变为字符串。快速修复。

于 2013-07-09T23:15:44.780 回答