无法使用ng-model选择下拉值第一项被选为空白

时间:2017-01-04 18:15:47

标签: javascript html angularjs

我试图通过将值设置为ng-model来选择AngularJS函数中的下拉值。但是当我在HTML中查找下拉时,首先选择空白值。这是我的HTML

<select class="pulldown" ng-model="test" ng-options="obj as obj.desc for identifier track by obj.value" ></select>
        <td><span style="padding-left:1px"></td></td></td> 

这是我在控制器中的Angular JS功能

$scope.modify = function(details){
$scope.identifier = [{"value" : "0","desc":"single"},{"value":"ABC","desc":""multiple"}]
$scope.test = details.employee ;
// Here details.employee can be ABC or 1 .Depending upon this ABC/1 I am trying to populate my HTML as Single / Multiple 
}

这是加载我选择空白值作为第一个。我希望填充值Single / multiple,具体取决于details.employee中我出错的位置。

2 个答案:

答案 0 :(得分:1)

更正您的ngOptions语法:

<select ng-options='obj.value as obj.desc for obj in identifier' ng-model='test'></select>

工作演示:

&#13;
&#13;
var myApp = angular.module('myApp',[]);


function MyCtrl($scope) {
    
    $scope.identifier = [
    {value : "0",desc:"single"},
    {value:"ABC",desc:"multiple"}
    ];
    
    $scope.test = $scope.identifier[0].value;
    
    $scope.getVal = function(test) {
      console.log(test);
    }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
    <select ng-model='test' ng-options='obj.value as obj.desc for obj in identifier' ng-change="getVal(test)"></select>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您定义了错误的ng-options

ng-options="obj as obj.desc for identifier track by obj.value"

所以改变你的:

<select class="pulldown" ng-model="test" ng-options="obj as obj.desc for identifier track by obj.value" ></select>

<select class="pulldown" name="test" ng-model="test" ng-options="obj.value as obj.desc for obj in identifier" >

现在它将按预期工作。请参阅jsfiddle link