1

我一直在尝试根据单选按钮选择过滤显示在下拉列表中的选项列表。

<div>
    <div ng-controller="sampleCtrl">
        <label>
            <input type="radio" name="type" ng-value="1" ng-model="selectedType" />A</label>
        <label>
            <input type="radio" name="type" ng-value="2" ng-model="selectedType" />B</label>
        <select ng-model="selectedOption" ng-options="option.id as option.name for option in options | filter:{type:selectedType}">
            <option value="">&lt;Select&gt;</option>
        </select>
        <hr/>
        <div>Type: {{selectedType}}</div>
        <div>Option: {{selectedOption}}</div>
    </div>
</div>

function sampleCtrl($scope) {

    $scope.selectedType = 1;

    $scope.selectedOption = 0;

    $scope.options = [{
        id: 1,
        name: 'bread',
        type: 1
    }, {
        id: 2,
        name: 'sugar',
        type: 2
    }, {
        id: 3,
        name: 'tea',
        type: 1
    }, {
        id: 4,
        name: 'coffee',
        type: 2
    }, {
        id: 5,
        name: 'butter',
        type: 2
    }];
}

这是jsFiddle

我有一个默认的 '' 选项,每次用户更改类型时都应该显示该选项。现在它会根据类型过滤我的选项。但是,当过滤器更改为 .

请帮忙。

谢谢。

4

2 回答 2

2

我认为这就是你需要的:小提琴

基本上,当用户通过在单选按钮之间切换来更改类型时,watch将触发将重置所选选项。

因此,在更改类型时,它确保与所选选项关联的模型被重置。

$scope.$watch('selectedType', function (newValue, oldValue) {
    if (newValue !== oldValue) {
        $scope.selectedOption = null;
    }
});
于 2013-08-26T15:03:01.960 回答
1

简化@callmekatootie 的回答:

您不需要参数newValueoldValue在这种情况下:

$scope.$watch('selectedType', function() {
    $scope.selectedOption = 0;
});

由于在加载期间触发,我也从$scope.selectedOption = null回更改为初始值。$watch这可以防止以后出现其他问题。

小提琴

于 2013-08-26T15:18:49.467 回答