【问题标题】:How to select AngularJS model on first time load?如何在第一次加载时选择 AngularJS 模型?
【发布时间】:2013-04-04 17:07:54
【问题描述】:

我正在使用 AngularJS 来填充选择选项列表。

默认情况下,我会根据字段 isMandatory 选择一个选项。 但问题是我无法在第一次加载时获取所选项目的 id。

当我更改选项时它会起作用。

请检查这个 plunker 代码:http://plnkr.co/edit/U2dVeo1vwZZPFKVhPleV?p=preview

【问题讨论】:

    标签: javascript angularjs angularjs-scope


    【解决方案1】:

    我建议使用 ng-options:

    <select ng-model="selectedItem" ng-options="item.id as item.text for item in list">
    

    还有一个设置初始选择项的函数:

    angular.forEach($scope.list, function(item, key){
      if(item.isMandatory) {
        $scope.selectedItem = item.id;
      }
    });
    

    Plunker

    【讨论】:

    • 我正在使用 $resource 来获取项目,可能是因为该控件永远不会进入 forEach 内部。我该怎么办?
    • @LittleLebowski,将 forEach 放在 query() 回调函数中。 (您也可以$watch list 进行更改,并将 forEach 放在手表回调中。)
    • 我将其标记为正确答案,因为它有效,但在我的情况下,我将使用 AngularUI-Select2 声明该指令不适用于 ng-options 并建议使用 ng -重复。此解决方案使用 ng-repeat 的任何解决方法?
    • @LittleLebowski,只需将 forEach 添加到原始 Plunker 中的控制器中即可设置初始模型值。见this Plunker。在这个新的 plunker 中,我还将数字转换为字符串,因为在 ng-repeat 中,值是字符串,而不是数字。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多