【问题标题】:How to populate value in a select dropdown as default using angular js如何使用angular js在选择下拉列表中填充值作为默认值
【发布时间】:2013-07-02 09:42:03
【问题描述】:
 <select data-ng-model="userInf.role" class="span12" required>
    <option value="" selected="selected" disabled="disabled">Choose one</option>
    <option data-ng-repeat="role in roles" value="{{ role.text }}">{{ role.text }}</option>
</select>

角度

userService.getUser($scope.userInf,
        function( data ) // success
        {

        $scope.userInf = {
                username: data.userName,
                firstname: data.firstName,
                middlename: data.middleName,
                lastname: data.lastName,
                title: data.title,
                organization: data.organization,
                role: data.authorization.role,
                dateOfBirth:data.dateOfBirth,
                save: 'update'              
            };
        },

其他字段即将到来,但选择值未到来

在检查元素中我可以看到

<select data-ng-model="userInf.role" class="span12 ng-pristine ng-valid ng-valid-required" required="">
        <option value="? string:Analyst ?"></option>
        <option value="" selected="selected" disabled="disabled">Choose one</option>
        <!-- ngRepeat: role in roles --><option data-ng-repeat="role in roles" value="Analyst" class="ng-scope ng-binding">Analyst</option>
        <option data-ng-repeat="role in roles" value="Admin" class="ng-scope ng-binding">Admin</option>
        </select>

【问题讨论】:

  • 你用的是IE9浏览器吗?

标签: javascript jquery html angularjs


【解决方案1】:

我知道 Angular 有 ng-init 指令就是为了这个目的。你为什么不试试 ng-options 指令?您可以将 ng-init 指令与 ng-options 一起使用,并且 ng-options 比 ng-repeat 更灵活。

<select ng-model="userInf.role" ng-options="role for role in roles" ng-init="userInf.role = '' " class="span12 ng-pristine ng-valid ng-valid-required" required="">
    <option value="" disabled="disabled">Choose one</option>
</select>

ng-init 会将您的 ng-model(下面定义的选项的值)设置为您想要的任何值,在这种情况下,将您的 ng-model 设置为 '',这是您的第一个选项的值。 ng-options 将使用数组中的值为您填充其余选项。您可能需要一些设置才能在选项中显示正确的名称和值。看这里https://docs.angularjs.org/api/ng/directive/select

【讨论】:

    【解决方案2】:

    是的,我会这样做:

    
    var app = angular.module('app', [])
    app.controller('exampleCtrl', function ($scope) {
      $scope.options = ["a", "b", "c"]
      $scope.selected = $scope.options[1]
    })
    <select ng-options="o for o in options" ng-model="selected"></select>      
    

    选项“b”将在加载时选择

    【讨论】:

      【解决方案3】:
      <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
            <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
          </select>
      

      【讨论】:

        猜你喜欢
        • 2019-06-27
        • 1970-01-01
        • 1970-01-01
        • 2018-04-11
        • 1970-01-01
        • 2022-06-22
        • 1970-01-01
        • 1970-01-01
        • 2011-06-25
        相关资源
        最近更新 更多