【问题标题】:Set dropdown default based on separate variable in Angular根据Angular中的单独变量设置下拉默认值
【发布时间】:2016-04-08 03:43:43
【问题描述】:

我有一个包含一些依赖项的下拉列表。我已经设法从数据集中填充列表并正确过滤它。下一步是选择默认值。这很复杂,因为默认设置在其他地方,所以我需要通过选项,看看它是否与定义的默认匹配并设置它,否则保持它没有默认。

我的数据集在 ng-repeat 中被过滤,只保留与变量 $scope.require = MUST 关联的值。

这是第一个下拉菜单的模板:

ng-repeat="option in firstList | filter: require: true" 

我有一个来自不同数据集的变量,它说明下拉菜单的默认值应该是什么。如果option in firstList 等于这个默认数字defnum,它应该是下拉菜单的默认值。

所以如果 defnum = 4,我希望下拉列表中的默认值是最后一个条目,其中 DefCom = 4。

"success" : true,
    "data" : 
        "this_info" : [{
                 "Req" : "MUST",
                 "DefCom" : "1",
}, {
                 "Req" : "NoMUST",
                 "DefCom" : "5"
}, {
                 "Req" : "MUST",
                 "DefCom" : "4"
}]}

有没有办法在 ng-model 中做到这一点,还是我必须编写一个 angular.forEach 循环?我尝试编写 angular.forEach 循环,但我只想循环遍历已在 ng-repeat 中过滤的值,我不想重写该过滤器(除非我必须这样做)。

【问题讨论】:

  • 您应该使用ng-options 而不是ng-repeat,以及ng-model。当您将 ng-model 属性设置为一个值时,如果该值出现在下拉列表中,它会自动将下拉菜单设置为该行项目的默认值。

标签: javascript angularjs angularjs-ng-repeat default angularjs-filter


【解决方案1】:

您可以使用 Angular 的 ng-selected 属性来设置基于另一个范围变量的选项的选择,如下所示:

  <option ng-selected="defnum == option.DefCom" ng-repeat="option in this_info | filter:{Req:'MUST'}:true">
    {{ option.DefCom }}
  </option>

plnkr.co demo

【讨论】:

  • @jenryb - 抱歉,应该使用 ng-selected。我更新了答案和the plnkr
【解决方案2】:

我不知道这是否有帮助...但我能够根据根深蒂固的属性/对象进行过滤以帮助进行搜索过滤。

这可能是您正在寻找的方向,或者至少将理论应用于您的问题。

<ul ng-repeat="x in gamesList | filter:{attributes: {gameData : {vsTeam: searchText}}}" class="item item-button-right"> .....

</ul>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-28
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 2021-08-15
    • 2021-04-13
    • 2018-09-29
    相关资源
    最近更新 更多