【问题标题】:How to select specific option using ng-options如何使用 ng-options 选择特定选项
【发布时间】:2014-04-10 16:15:47
【问题描述】:

我从一系列来源开始

$scope.sources = [
        {
            "type": "register",
            "name": "Register 1",
            "balance": 100
        },
        {
            "type": "register",
            "name": "Register 2",
            "balance": 100
        },
        {
            "type": "register",
            "name": "Register 3",
            "balance": 200
        },
        {
            "type": "office",
            "name": "Change Drawer",
            "balance": 200
        },
        {
            "type": "office",
            "name": "Safe",
            "balance": 500
        }
];

我正在成功加载选项

<div class="form-group">
    <label>Transfer <strong>{{amount(count, start, selectedItem.balance) | currency}}</strong> To:</label>
    <select id="transferTo" class="form-control" ng-model="form.to" ng-options="item.name for item in sources | filter:{type:'office'}">
        <option value="">-- Select a Source --</option>
    </select>
</div>

我尝试使用$timeout 函数在它工作后选择它,但它没有将正确的值传回我的函数

$timeout(function () {
    $('#transferTo').val('1');
}, 200);

如何将“安全”设置为表单加载时选择的默认选项?

【问题讨论】:

  • 您希望将form.to 设置为什么值?为了唯一标识每个选项。
  • 您需要将form.to范围属性设置为选定的值。
  • 我真的需要整个对象回来。我确实有item.balance as item.name for item in sources | filter:{type:'office'},它把余额传回来了,但我需要整个对象来更新范围
  • 然后,您需要将form.to 设置为“安全”数组对象。因为它将使用对象引用来比较选定的值。您还可以查看track by 子句中的ng-options
  • @DavinTryon 关于使用track by 的好点子,因为它将允许您从本质上指定一个字段来为所选项目进行匹配

标签: angularjs ng-options


【解决方案1】:

你需要在你的作用域上设置一个值,你设置 ng-model 等于:

$scope.form.to = $scope.sources[4];

如果您的列表(来源)是动态的,您可以像这样过滤数组,这将返回一个数组(但保持您的数组不变)。

filterFilter($scope.sources, {name: 'Safe'})

fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-06
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多