[英]angularjs -Setting the selected value in a select dropdown when editing an item
How can I set the selected value of a dropdown when I edit an item ? 编辑项目时如何设置下拉菜单的选定值?
<div class="form-group">
<label for="category" class="col-sm-2 control-label">Category</label>
<div class="col-sm-10">
<select ng-model="quiz.category" ng-options="category as category.name for category in categories" required>
<option></option>
</select>
</div>
</div>
And when I click on edit 当我点击编辑
$scope.editQuiz = function(quiz)
{
$scope.quiz = {};
$scope.quiz.name = quiz.name // this works fine
$scope.quiz.category = quiz.category[0]; // ?????
console.log($scope.quiz.category);
//$scope.quiz = quiz;
}
Method to get categories: 获取类别的方法:
$scope.getCategories = function() {
$http.get('http://localhost/myappi/API/index.php/Api/categories').
success(function(data) {
$scope.categories = data;
})
.error(function(err) {
console.log('error',err);
})
};
Changing the select's ngModel is definitely the way to go. 更改选择的ngModel绝对是正确的方法。 You can check out this solution , since I believe it deals with the same problem.
您可以查看此解决方案 ,因为我认为它可以解决相同的问题。
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }]; $scope.selectedOption = $scope.options[1];
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
Can you send us your data structure sample? 您可以将您的数据结构样本发送给我们吗?
Ok if you really want to keep quiz.category as an array. 好吧,如果您真的想将quiz.category保留为数组。
At first when you get
the quiz assign quiz.category
to an new object. 首先,当您
get
测验时,请将quiz.category
分配给新对象。 eg: 例如:
$scope.tmp = { category: quiz.category[0] };
We have to do that since quiz.category
is an array but the value of the ng-options
is an object. 我们必须这样做,因为
quiz.category
是一个数组,但是ng-options
的值是一个对象。
now we can bind that var to the options like this: 现在我们可以将该var绑定到以下选项:
<select ng-model="tmp.category" ng-options="category as category.name for category in categories" required>
<option></option>
</select>
and finally in your function you replace the old value with the new: 最后在函数中,将旧值替换为新值:
$scope.quiz.category[0] = tmp.category;
Hope it makes sense 希望有道理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.