2013-08-26 120 views
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

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

请大家帮忙。

谢谢。

+0

我无法理解你的问题 - 你的意思是指出哪里,从B选项更改为A时,选择模型不复位,仍然保持之前选择的行为? – callmekatootie

+0

是的。这就是我的意思。对不起,如果我的问题不够清楚。 – vaibinewbee

回答

2

我觉得这是你所需要的:Fiddle

基本上,当用户通过单选按钮之间进行切换改变类型,watch将被触发,将重置所选选项。

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

$scope.$watch('selectedType', function (newValue, oldValue) { 
    if (newValue !== oldValue) { 
     $scope.selectedOption = null; 
    } 
}); 
+0

是的,这是我想要的。谢谢@callmekatootie! – vaibinewbee

1

简化@ callmekatootie的回答是:

你并不需要的参数newValueoldValue在这种情况下:

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

我也是从$scope.selectedOption = null回到初始化值改变,因为$watch是onload时触发。这可以防止其他问题。

Fiddle

+0

如果我不检查newValue和oldValue,它会一直改变它。不是我想要的东西。还是)感谢你的建议。 – vaibinewbee

+0

@vaibinewbee你的意思是,如果你是在A型,并点击A型,它会改变它为默认?如果这就是你所指的那么那是不正确的,因为单选按钮的值只在另一个单选按钮被选中时才会改变。我不确定自己明白。我的JsFiddle与提供的值和代码的callmekatootie完全相同。除非我错过了一些东西。 – jnthnjns

+0

好吧,这是一个非常独立的例子。查看更大的图片,例如,当您修改现有数据模型中的数据时,并根据对象上的现有属性在下拉列表中设置所选值。在这种情况下,首次加载视图时,它将始终将其设置为null。这是我想要做的事情。所以它不适合我。正如我所说,我喜欢你的建议。 – vaibinewbee