如何使用ng-options选择特定选项

时间:2014-04-10 16:15:48

标签: angularjs ng-options

我从一系列来源开始

$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);

我如何设置&#34; Safe&#34;作为表单加载时选择的默认选项?

1 个答案:

答案 0 :(得分:3)

您需要在示波器上设置一个值,该值设置的ng-model等于:

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

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

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

fiddle