使用ng-options时,Ng-model作用域不可用

ng-model scope not available while using with ng-options

本文关键字:作用域 Ng-model ng-options 使用      更新时间:2023-09-26

我只是想实现一个简单的下拉,这里是我的代码

<select ng-change="selectTestSuite();" ng-model="testCase" ng-options="testSuite.TEST_NAME for testSuite in publicTestCase"></select>

在控制器中,当我试图在控制台中打印testCase的值时,它正在给出未定义。但是当我尝试使用

打印testCase的id时
{{testCase.TEST_ID}}

它给了我id。我也检查了使用$watch

$scope.$watch('testCase',function() {
   console.log($scope.testCase);
});

无法找出我犯错误的地方。谢谢你的帮助。

我认为ng-options没有问题。

实际上ng-options映射了"testSuite"。TEST_NAME"作为模型到ng-model.

确保"testSuite"。

"TEST_NAME"是否在"publicTestCase"集合中可用(是否未定义)。

您正在将testCase绑定到testSuite.TEST_NAME。你的ng-options应该像这样:

<select ng-change="selectTestSuite()" ng-model="testCase" ng-options="testSuite as testSuite.TEST_NAME for testSuite in publicTestCase"></select>

模型从publicTestCase数组中的记录绑定到testSuite的值,并且对于每个您想要的testSuite。TEST_NAME显示为选项文本。

输入图片描述

注意:-请找到图像链接。图像包含代码ng-repeat指令为数组中的每一项重复一段HTML代码,它可以用来在下拉列表中创建选项,但ng-options指令是专门为用选项填充下拉列表而设计的,它至少有一个重要的优点:

使用ng-options创建的下拉列表允许选择的值是一个对象,而使用ng-repeat创建的下拉列表必须是一个字符串。