如何从javascript / angularjs中选择一个选项

时间:2015-06-27 12:24:42

标签: javascript angularjs

如何从javascript / Angularjs后端选择<select>标记选项。

提示:我实际上从API服务获取数据,然后填写表单以使其可供编辑。假设性别是男性,我怎样才能使<select> tage成为男性,因为它在数据库中。因此,用户可以将其更新为女性。

这是我的代码:

  $scope.Gender = [
    { GenderID: "Mmale", name: "Mmale" },
    { GenderID: "Female", name: "Female" }
    ];

//Assigning data to select tag. But this did not work for me:
$scope.Gender.name = $scope.users[id].Gender;
$scope.Gender.GenderID = $scope.users[id].Gender;
 <select class="form-control" name="Gender" ng-model="GenderID" ng-options="g.GenderID as g.name for g in Gender" required style="width:98px; color:gray">
                        <option value="" style="" >Gender?</option>
                    </select>
<input type="button" value="SelectMale()">

2 个答案:

答案 0 :(得分:2)

你的意思是这样的:

$scope.selectMale = function() {
    $scope.GenderId = "Mmale"; 
}

Working plunke

答案 1 :(得分:1)

如果您想查看所选值,可以使用 ng-change 将代码编写为:

<select class="form-control" name="Gender" ng-model="GenderID" ng-options="g.GenderID as g.name for g in Gender" ng-change="Selectmale(g.GenderID)" required style="width:98px; color:gray"> 
  <option value="" style="" ></option>
</select>

$scope.Selectmale=function(genderId){
  console.log(genderId) //this will return the current genderId
}