在选择框angularjs中设置选定的值

时间:2015-04-15 12:43:17

标签: javascript angularjs

我有一个选择框,其中的选项从我的后端填充。

<tr>
    <td class="col-lg-4">Superkund</td>
    <td><select class="form-control input-sm2" ng-model="selectedSupercustomer" ng-options="item as item.namn for item in superkundOptions" ng-change="onChangeSuperCustomer(selectedSupercustomer)"></select></td>
</tr>

 $http.get($rootScope.appUrl + '/nao/abb/getSuperkundData/' + $rootScope.abbForm).success(function(data) {
            $scope.superkundOptions = data;
        });

我遇到的问题是第一行是一个空行,我想用选定的值替换该空。我试过这个:

$scope.selectedSupercustomer = "fish"

但那不起作用。谁可以帮助我?

3 个答案:

答案 0 :(得分:1)

选择框与引用一起使用。这意味着,您必须将模型$scope.selectedSupercustomer设置为$ scope.superkundOptions [ID / INDEX_OF _&#34; fish&#34;]。

答案 1 :(得分:0)

使用ng-init。例如,ng-init为所选的第一个项目:

<select ng-init="selectedSupercustomer = superkundOptions[0]" ... ></select>

JSFiddle Example

答案 2 :(得分:-1)

你可以看看这个例子

HTML:

<div ng-app="myApp" ng-controller="SomeController">
    <div ng-repeat="Person in People">
        <div class="listheader">{{Person.firstName}} {{Person.lastName}}</div>
        <div class="listitem" ng-repeat="Choice in Person.Choices">
            {{Choice.Name}}: 
            <select 
                ng-model="Choice.SelectedOption"                 
                ng-options="choice.Name for choice in Choice.Options track by choice.ID"></select>
            {{Choice.SelectedOption.ID}}
        </div>
    </div>
</div>

JavaScript的:

var myApp = angular.module('myApp', []);
myApp.controller("SomeController", function($scope) {
    $scope.People = [{
        "firstName": "John",
        "lastName": "Doe",
        "Choices": [
            {
                "Name":"Dinner",
                "Options":[{Name:"Fish",ID:1}, {Name:"Chicken",ID:2}, {Name:"Beef",ID:3}],
                "SelectedOption":{Name:"Chicken",ID:2}
            },
            {
                "Name":"Lunch",
                "Options":[{Name:"Macaroni",ID:1}, {Name:"PB&J",ID:2}, {Name:"Fish",ID:3}],
                "SelectedOption":""
            }
        ],        
    }, {
        "firstName": "Jane",
        "lastName": "Doe"
    }];
});

CSS:

body{
    font-family: verdana;
    font-size: 10pt;
}

.listheader{
    font-weight: bold;
    text-decoration: underline;
    padding-top: 5px;
}

fiddle link