6

Trying to figure out why the model does not update when the bound selected option no longer exists. I would expect the model's property to update to undefined/null/empty string.

Situation: One select drives another select using filter. After selections are made, go to the original select and choose another option. Filter will remove the second select option as expected, but the model property on the second select will be unchanged.

Problem: When you go to pass the model, it will be populated with bad/previous values. In addition, using Angular validation, the select being required...the form is technically "valid" because the model has a value (the previous value) for the property.

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>

Model:

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"
   }];
});

I'm fairly certain I could tie an ng-change function to the first to force it to update the model, but is there a better way?

Example Plunker demonstrating the problem

Andrew
  • 63
  • 4

1 Answers1

6

Try this way:

$scope.$watch('selectedCategory', function(selectedCategory){
    $scope.selectedSubCategory = null;
});
karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • Yes this technically works, but adding a $watch to each tied select could become expensive, no? Is there a better/cleaner way? – Andrew Sep 18 '14 at 18:12
  • Andrew, I think this is right solution for your case. 1 watcher for 1 select - it's OK – Alexey Sep 18 '14 at 18:16
  • @Andrew Dickerson Your other option is as you outlined at the end of your question -- you can simply force the state of the selectedSubCategory to effectively nothing. `ng-change="selectedSubCategory = ''"` – Matt Sep 18 '14 at 18:17
  • @AndrewDickerson This use case is interesting in that AngularJS shows the value of the model as valid when the options are changed. `` I think perhaps this is something that should be detected for in AngularCore, as the model should technically be `ng-invalid` since the model value no longer is an option. Pull request? – David Sung Lee Sep 18 '14 at 18:33
  • @DavidSungLee This is what concerned me as well. I would not expect it to be valid with no value present. – Andrew Sep 18 '14 at 18:36