【问题标题】:AngularJS ng-repeat setting default select valueAngularJS ng-repeat 设置默认选择值
【发布时间】:2014-02-16 14:09:41
【问题描述】:
$scope.activities =
    [
        { id: 1, type: "DROPDOWN_MENU", name: "Dropdown Menu" },
        { id: 2, type: "HORIZONTAL_BAR", name: "Horizontal Bar" }
    ];

<select data-ng-model="engineer.currentActivity" data-ng-options="a.name for a in activities">                
</select>

使用上面的方法,我可以创建一个包含 3 个值的选择框,一个空白,然后是下拉菜单和水平条。

我想将水平条设置为我的默认设置,但看不到如何执行此操作。

帮助会很大

【问题讨论】:

  • 顺便说一句,如果您最终要从服务器中提取activities,并且您需要对所选选项进行水合,则需要查看ng-options 表达式中的track by 表达式。

标签: angularjs select angularjs-scope angularjs-ng-repeat


【解决方案1】:

在您的角度控制器中:

$scope.activities = [
    { id: 1, type: "DROPDOWN_MENU", name: "Dropdown Menu" },
    { id: 2, type: "HORIZONTAL_BAR", name: "Horizontal Bar" }
];
$scope.activity = $scope.activities[1]; //Bind 2nd activity to the model.

在 HTML 中:

<select ng-model="activity" 
    ng-options="activity as activity.name for activity in activities">
    <option value=""></option>
</select>

见Fiddle

【讨论】:

    【解决方案2】:

    在控制器中,只需添加一行来设置初始选择:

    $scope.activities =
        [
            { id: 1, type: "DROPDOWN_MENU", name: "Dropdown Menu" },
            { id: 2, type: "HORIZONTAL_BAR", name: "Horizontal Bar" }
        ];
    
    $scope.engineer = {}; // if needed
    $scope.engineer.currentActivity = $scope.activities[1];
    

    【讨论】:

      【解决方案3】:

      使用ng-initdirective

      ng-init="engineer.currentActivity = options[1]"
      

      【讨论】:

        猜你喜欢
        • 2016-12-11
        • 1970-01-01
        • 2015-07-17
        • 2018-11-02
        • 2014-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多