[英]AngularJs, ng-options and default option showing blank
I have a ng-options, an array and a default ng-options-model of 0, ie the first element in the array. 我有一个ng-options,一个数组和一个默认的ng-options-model 0,即数组中的第一个元素。 Why is the first name in the array shown in the dropdown (it is only blank)?
为什么数组中的名字显示在下拉列表中(仅空白)?
I have this html: 我有这个HTML:
<form>
<select ng-options="index as contact.name for (index,contact) in contacts" ng-model="selectedContact"></select>
</form>
Selected contact array index (default 0): {{selectedContact}}
And this controller: 而这个控制器:
app.controller('MyCtrl', ['$scope', function ($scope) {
$scope.contacts = [
{email: "me@example.com", name: "Mini Me"},
{email: "you@example.com", name: "Maxi You"}
];
$scope.selectedContact = 0;
}]);
Your ng-options
syntax is a bit wrong, you're using the syntax for iterating an objects properties, when you actually have an array of objects: ng-options
语法有点错误,当实际上有对象数组时,您正在使用该语法来迭代对象属性:
ng-options="contact as contact.name for contact in contacts"
And then you set the index of the array to select the first one: 然后设置数组的索引以选择第一个:
$scope.selectedContact = $scope.contacts[0];
Ok, found the solution myself. 好的,我自己找到了解决方案。 ng-repeat has the index as a string (so selectedContact is a string), but my controller was using a number.
ng-repeat的索引为字符串(所以selectedContact是字符串),但是我的控制器使用的是数字。 When I change my controller to:
当我将控制器更改为:
$scope.selectedContact = "0";
Then it worked perfectly. 然后,它运行完美。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.