sh3nan1gans
sh3nan1gans

Reputation: 2356

Ng-model not reacting to change in chained ng-options

I am seeing some odd behavior when chaining select elements with ng-options built off of an array of objects. Fiddle here

The scope property "filter.option" does not get reset when changing the scope property "filter.general", but the drop-down does.

Mandatory code of the array:

$scope.filterData = [
{"name" : "Users", "options" : []},
{"name" : "Data calls", "options" : [{"title": "Collection"}, {"title": "User"}]},
{"name" : "Msg Pub", "options" : [{"title": "Topic"}, {"title": "User"}]},
{"name" : "Msg Sub", "options" : [{"title": "Topic"}, {"title": "User"}]}
];

I came up with a hack using ng-change that wipes "filter.option" to get the desired behavior. Fiddle here

Does anyone know why this is happening? It seems to be because the "filter.option" model is not bound to the "filter.general" model and therefore does not reflect any changes to the latter. Is there a way to build the second model off of the first one? Any help would be greatly appreciated.

Upvotes: 0

Views: 125

Answers (1)

pedalpete
pedalpete

Reputation: 21536

As I understand it, there is nothing in changing the 'filter.general' which is telling 'filter.option' to update.

Hopefully somebody else can say why, I seem to recall something about angular.js not liking to update values to null, but also, sometimes values just don't update like you hoped. Sorry I can't provide more info on the matter.

However, a solution, I have. Here's a jsfiddle. http://jsfiddle.net/ADukg/4643/

You need to do two things. First, use ng-change on your general field to tell angular when that field changes.

Then in your controller, have a 'reset' method which points to the first option in the select dropdown (the empty select). return $scope.filter.option = $scope.filter.option[0];

I know it seems weird, but I think this is what you're looking for.

Upvotes: 1

Related Questions