Angularjs 使用“角度”时如何设置“选择”的“值”属性

Angularjs 使用“角度”时如何设置“选择”的“值”属性,angularjs,Angularjs,我可以使用以下语法成功地将数组绑定到角度中的select标记:- var mainApp = angular.module('mainApp', []); mainApp.controller('mainController', [ '$scope', function ($scope) { $scope.testArray = [{ text: '1st', value: 1 }, { text: '2nd', value: 2 }]; }]); 我的HTML如下所示:- &l

我可以使用以下语法成功地将数组绑定到角度中的select标记:-

var mainApp = angular.module('mainApp', []);

mainApp.controller('mainController', [
'$scope',
function ($scope) {

    $scope.testArray = [{ text: '1st', value: 1 }, { text: '2nd', value: 2 }];

}]);
我的HTML如下所示:-

<select ng-model="testModel" ng-options="theTitle.text as theTitle.text for theTitle in testArray"></select>
<select ng-options="theTitle.text as theTitle.text for theTitle in testArray" ng-model="testModel" class="ng-pristine ng-valid">
  <option value="?"></option>
  <option value="0">1st</option>
  <option value="1">2nd</option>
</select>

但是,这会创建如下选项列表:-

<select ng-model="testModel" ng-options="theTitle.text as theTitle.text for theTitle in testArray"></select>
<select ng-options="theTitle.text as theTitle.text for theTitle in testArray" ng-model="testModel" class="ng-pristine ng-valid">
  <option value="?"></option>
  <option value="0">1st</option>
  <option value="1">2nd</option>
</select>

第一
第二
如何将数组中的value属性绑定到option-value属性,以及为什么它将第一个选项显示为


是否需要在我的ng选项属性中添加其他内容?

原因是什么?显示的原因是您的ngModel尚未初始化。在mainController中,将testModel初始化为“1st”。你会看到吗?此时,您的下拉列表将初始化为
ng options
中的第一项,格式为
value as alias
,因此您需要:

<select ng-model="testModel" ng-options="theTitle.value as theTitle.text for theTitle in testArray"></select>

创建
选项是因为您的模型值在“选择”中不作为选项存在,因此浏览器将其添加以将输入显示为空。要解决此问题,您需要将模型初始化为有效值,例如:
ng init=“testModel=testArray[0]。html部分中的值“

<select ng-model="testModel" ng-options="theTitle.text for theTitle in testArray"></select>

谢谢,这几乎给了我完整的答案。我只需要添加track by theTitle.value来获得绑定到数组的值。所以我有:-ng options=“testArray中的title的title.text按title.value跟踪”您可以使用ng change在select标记中捕获操作。select标记的值是
$scope.testModel.Value