gpt4 book ai didi

javascript - 选择下拉列表最初不绑定(bind)到 AngularJS 模型

转载 作者:搜寻专家 更新时间:2023-11-01 05:10:37 25 4
gpt4 key购买 nike

好的,我的问题是我有一个简单的选择下拉菜单,并且我使用 ng-repeat 来填充下拉菜单,如下所示:

<select ng-model="tstCtrl.model.value" required>
<option ng-repeat="option in tstCtrl.myOptions" value="{{option.a}}">{{option.b}}</option>
</select>

选择一个选项后,绑定(bind)到 model.value 工作正常,但在那之前它似乎没有将选定的下拉选项绑定(bind)到值 model.value 最初设置为。

如下所示:

<!DOCTYPE html>
<html>

<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>

<script>
angular.module('Test', []).controller('TestController', function(){

this.model = {
value:3
};

this.myOptions = [
{a:1, b:"one"},
{a:2, b:"two"},
{a:3, b:"three"},
{a:4, b:"four"},
{a:5, b:"five"}];
});
</script>
</head>

<body ng-app="Test" ng-controller="TestController as tstCtrl">

{{tstCtrl.model.value}}

<select ng-model="tstCtrl.model.value" required>
<option ng-repeat="option in tstCtrl.myOptions" value="{{option.a}}">{{option.b}}</option>
</select>

</body>



</html>

我认为上面的代码片段非常清楚,但很乐意回答任何问题。

我该如何解决?

谢谢

最佳答案

我建议您在选择中使用 ng-options 语法而不是 ng-repeat。如果您想显示属性 b 但绑定(bind)到属性 a 您可以使用以下语法:

<select ng-model="model.value" ng-options="option.a as option.b for option in myOptions" required>      
</select>

这是您修改后的工作代码段:

<!DOCTYPE html>
<html>

<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>

<script>
angular.module('Test', []).controller('TestController', function($scope){

$scope.model = {
value:3
};

$scope.myOptions = [
{a:1, b:"one"},
{a:2, b:"two"},
{a:3, b:"three"},
{a:4, b:"four"},
{a:5, b:"five"}];
});
</script>
</head>

<body ng-app="Test" ng-controller="TestController">

{{model.value}}

<select ng-model="model.value" ng-options="option.a as option.b for option in myOptions" required>
</select>

</body>



</html>

关于javascript - 选择下拉列表最初不绑定(bind)到 AngularJS 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32871790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com