Reputation: 222522
I have JSON like this,
$scope.analytics = {
'Twitter': [
'Following',
'Followers',
'Tweets'
],
'Facebook': [
'People engaged',
'Likes',
'Clicks',
'Views'
],
'LinkedIn': [
'Overview'
]
};
From the above, I need to create a cascading md-select , First md-select should have Twitter,Facebook and Linkedin.
OnChanging Twitter, it should display the Following,Followers,Tweets in the next md-select.
HTML:
<md-select ng-model="type" >
<md-option ng-value="t" data-ng-repeat="t in analytics">{{ t }}</md-option>
</md-select>
<md-select ng-model="metrics" >
<md-option ng-value="t" data-ng-repeat="t in analytics">{{ t }}</md-option>
</md-select>
App.JS:
app.controller('MainCtrl', function($scope) {
$scope.analytics = {
'Twitter': [
'Following',
'Followers',
'Tweets'
],
'Facebook': [
'People engaged',
'Likes',
'Clicks',
'Views'
],
'LinkedIn': [
'Overview'
]
};
});
Here is my code in Cascading md-select
Upvotes: 0
Views: 1729
Reputation: 189
It may be simpler than that. Delete the $watch
and just change the ng-repeat
in the md-options
item for metrics
<md-select ng-model="type">
<md-option ng-value="k" data-ng-repeat="(k,v) in analytics">
{{ k }}
</md-option>
</md-select>
<md-select ng-model="metrics">
<md-option ng-value="t" data-ng-repeat="t in analytics[type]">
{{ t }}
</md-option>
</md-select>
Upvotes: 1
Reputation: 40296
The key to solving this is to place a watch on the value of the first select and control the options of the second. Also remember to clear the dependent selection, when the master selection changes!
A sample implementation:
Add a level2
variable in the scope. It will hold the options of the dependent select.
Place the watch on the first model:
$scope.$watch('type', function(newval, oldval) {
if( newval ) {
$scope.level2 = $scope.analytics[newval];
}
else {
$scope.level2 = [];
}
// delete the dependent selection, if the master changes
if( newval !== oldval ) {
$scope.metrics = null;
}
});
Finally the markup needs a little tweaking to display correctly:
<md-select ng-model="type" >
<md-option ng-value="k" data-ng-repeat="(k,v) in analytics">{{ k }}</md-option>
</md-select>
<md-select ng-model="metrics" >
<md-option ng-value="t" data-ng-repeat="t in level2">{{ t }}</md-option>
</md-select>
See a forked plunk: http://plnkr.co/edit/rI3AsC2plZ3w82WRBjAo?p=preview
Upvotes: 3