【问题标题】:AngularJS: selecting option from dropdown menuAngularJS:从下拉菜单中选择选项
【发布时间】:2023-03-29 12:31:01
【问题描述】:
这是我的代码:
<select class="form-control" name="author" ng-options="author as author.fullname for author in authors" ng-model="author" ng-required="true"></select>
如何更改控制器中的选定值?
【问题讨论】:
标签:
angularjs
angularjs-ng-options
【解决方案1】:
Angular 适用于“双向绑定”。 ng-model="author" 将您的下拉列表绑定到 $scope.author,因此下拉列表或控制器的更改将反映在这两个位置,因此绑定。
所以从你的 ng-options 我假设你有一个名为 author 类型的数组 author 所以在你的控制器中只是
$scope.author = $scope.authors[0];
请记住,在控制器中,您需要在变量之前使用$scope.,而在 html ng-model 或其他 ng 指令中,您不需要 $scope。前缀
【解决方案2】:
只需将$scope.author 设置为您想要的任何author,例如:
$scope.author = $scope.authors[2];
这是一个例子jsBin
或者查找作者的一些方法(按名称、id?)并将$scope.author 或其他任何值设置为该值。