【问题标题】:Prevent initial select option being blank in Angular防止 Angular 中的初始选择选项为空
【发布时间】:2013-12-07 21:49:25
【问题描述】:

我有一些简单的角度代码,它呈现一个表单并使用数组中的选项填充一个选择框:

html:

<form class="form-horizontal">
  <div class="control-group">
      Title: <br />
      <input ng-model="new_project.title" type="text" id="title" class="form-control" placeholder="Title" >
      Created By: <br />
      <select data-ng-options="o.name for o in assignedToOptions" data-ng-model="new_project.created_by" id="created_by" class="form-control"></select>
  </div>
  ...
</form>

js:

$scope.getUsers = function () {
    ConcernService.list('users/').then(function(data) {
        $scope.users = data;
        // assign user list to select options
        $scope.assignedToOptions = [];
        i = 0;
        while (i < data.length) {
            $scope.assignedToOptions.push({ name: data[i].id, name: data[i].username });
            i++;
        };
    });
};

这一切都很好,但 Angular 总是在选择字段中放置一个空白选项。消除空白选项的最佳方法是什么?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    要消除空白选项,您需要确保选择模型具有初始值。

    你可以在控制器中设置:

    $scope.new_project = 
        {
          created_by: $scope.assignedToOptions[0]
        };
    

    或者通过将以下属性添加到选择元素:

    ng-init="new_project.created_by = assignedToOptions[0]"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      • 2016-09-17
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多