6

试图找出为什么当绑定选定选项不再存在时,模型不会更新。我期望模型的属性更新为undefined/null /空字符串。筛选出选择选项后,角度模型无法更新

情况:一个select使用过滤器驱动另一个select。选择完成后,转到原始select并选择其他选项。过滤器将按预期移除第二个select选项,但第二个select上的模型属性将保持不变。

问题:当你去传递模型时,它将被填充坏/先前的值。此外,使用Angular验证,需要select ...该表单在技术上是“有效的”,因为该模型具有该属性的值(以前的值)。

HTML:

<select name="Category" ng-model="selectedCategory" 
     ng-options="item.name as item.name for item in categories"> 
    <option value="">All Categories</option> 
</select> 

<select name="SubCategory" ng-model="selectedSubCategory" 
     ng-options="item.name as item.subCategory for item in categories | filter:selectedCategory"> 
    <option value="">All SubCategories</option> 
</select> 

型号:

app.controller('MainCtrl', function($scope) { 
    $scope.categories = [{ 
     "id": "1", 
     "name": "Truck", 
     "subCategory": "Telescope" 
    }, { 
     "id": "2", 
     "name": "Truck", 
     "subCategory": "Hazmat" 
    }, { 
     "id": "3", 
     "name": "Van", 
     "subCategory": "Mini" 
    }]; 
}); 

我相当肯定,我可以扎一个NG-改变功能,第一,迫使它更新模型,但有一个更好的方法?

Plunker演示问题

回答

6

试试这个方法:

$scope.$watch('selectedCategory', function(selectedCategory){ 
    $scope.selectedSubCategory = null; 
}); 
+0

是的,这在技术上的工作,但增加了$手表各绑选择可能变得昂贵,不是吗?有更好的/更清洁的方式吗? – Andrew 2014-09-18 18:12:08

+0

安德鲁,我认为这是你的情况的正确解决方案。 1个选择器 - 1个选择 - 没关系 – Alexei 2014-09-18 18:16:40

+0

@Andrew Dickerson您的其他选项与您在问题结束时列出的一样 - 您可以简单地强制selectedSubCategory的状态为无效。 @ ng-change =“selectedSubCategory =''”' – Matt 2014-09-18 18:17:54