【问题标题】:AngularJs, ng-options and default option showing blankAngularJs、ng-options 和默认选项显示空白
【发布时间】:2014-12-17 14:21:52
【问题描述】:

我有一个 ng-options、一个数组和一个默认为 0 的 ng-options-model,即数组中的第一个元素。为什么下拉列表中显示数组中的名字(它只是空白)?

plunk

我有这个 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}}

还有这个控制器:

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;
}]);

【问题讨论】:

    标签: angularjs ng-options


    【解决方案1】:

    您的 ng-options 语法有点错误,当您实际上有一个对象数组时,您正在使用该语法来迭代对象属性:

    ng-options="contact as contact.name for contact in contacts"
    

    然后你设置数组的索引选择第一个:

    $scope.selectedContact = $scope.contacts[0];
    

    【讨论】:

    • 名字其实不是唯一的。由于所选选项使用数组索引的原因,我已经看到了这种对数组进行迭代的方式...
    • @EricC - 您应该使用上述语法,使用 $index 从上述语法中获取索引 - 然后将其设置为实际数字即可。
    【解决方案2】:

    好的,我自己找到了解决方案。 ng-repeat 将索引作为字符串(因此 selectedContact 是字符串),但我的控制器使用的是数字。当我将控制器更改为:

    $scope.selectedContact = "0";
    

    然后它完美地工作了。

    【讨论】:

      猜你喜欢
      • 2014-07-26
      • 2016-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多