从角度过滤器设置默认选项

时间:2016-01-07 03:03:58

标签: angularjs

我有一个使用过滤器生成的选择列表:

<select ng-model="item.SAC">
    <option ng-repeat="code in SACCodes | filter:{group: item.SACGroup}" value="{{code.code}}">{{code.code}} - {{code.description}} - {{code.group}}</option>
</select>

item.SACGroup更改时,我想自动选择第一个有效选项(以便选择框永远不会变为空白)。

$scope.SACCodes = [
{'code':'034', 'description':'FTG Support Steel', 'group':'footings'},
{'code':'037', 'description':'Masonry Wall FTGs', 'group':'footings'},
{'code':'032', 'description':'S.O.G. Rebar', 'group':'slabs'},
{'code':'033', 'description':'S.O.G. (DBL.Mat)', 'group':'slabs'}
];

1 个答案:

答案 0 :(得分:0)

以下是WORKING JSBIN示例:

<强>解释

正如@AnikIslamAbhi的评论中指出的那样,你应该在这里使用ng-options

<select ng-model="item.SAC" ng-options="code.code as codeLabel(code.code, code.description, code.group) for code in SACCodes | filter:{group: item.SACGroup}">
</select>

在您的范围内定义codeLabel方法:

$scope.codeLabel = function(code, description, group) {
  return code + " - " + description + " - " + group;
};

有关设置默认选项值的原始问题,请将ng-init添加到<select>元素:

<select ng-model="item.SAC" ng-options="code.code as codeLabel(code.code, code.description, code.group) for code in SACCodes | filter:{group: item.SACGroup}" ng-init="item.SAC = SACCodes[0].code">
</select>

希望它对你有所帮助。