Reputation: 291
I watched a video at http://www.bennadel.com/blog/2452-Mixing-Static-And-Dynamic-Data-In-An-AngularJS-Select-Menu.htm and it is almost getting me what I need. This Pluncker http://plnkr.co/edit/iy8mdpyg40ot8KEaOjz6?p=preview has an example of how I have a couple of select options set up with AngularJS. I want to be able to set the option of either/both of the select list by changing the model or just a click event would be enough to get me going.
Upvotes: 0
Views: 129
Reputation: 60396
While select
element historically restricts your options
to only have a string value, ngOptions directive allows you to use full-blown objects as <option>
value.
But one must remember that ngOptions
will use strict comparison when comparing the objects from the list with the object in pre-selected model.
This means that, when pre-selecting your model, you must set it to exact same instance of the selected object from the iterated list:
app.controller('MainController', function($scope) {
$scope.options1 = [
{id: 1, label: 'label1', type: 'type1', parentType: 'parentType1'},
{id: 1, label: 'label2', type: 'type2', parentType: 'parentType1'},
{id: 1, label: 'label3', type: 'type3', parentType: 'parentType2'},
{id: 1, label: 'label4', type: 'type4', parentType: 'parentType2'},
{id: 1, label: 'label5', type: 'type5', parentType: 'parentType3'}
];
$scope.type = "";
$scope.options2 = [
{id: 1, label: 'specialLabel1', type: 'label1', parentType: 'parentType1'},
{id: 1, label: 'specialLabel2', type: 'label1', parentType: 'parentType2'},
{id: 1, label: 'specialLabel3', type: 'label2', parentType: 'parentType3'},
{id: 1, label: 'specialLabel4', type: 'label2', parentType: 'parentType4'},
{id: 1, label: 'specialLabel5', type: 'label3', parentType: 'parentType5'}
];
$scope.get = function(myarray, type) {
return myarray.filter( function(value, index, arr) {
return value.type == type.label
});
}
$scope.select = function () {
$scope.type = $scope.options1[2];
}
});
<body ng-app="myApp" ng-controller='MainController'>
<select
ng-model="type"
ng-options="p as p.label group by p.parentType for p in options1"
></select>
<select
data-ng-model="speciality"
ng-options="p as p.label group by p.type for p in get(options2, type)"
>
<option value="">None</option>
</select>
<hr />
<button ng-click="select()">Set type</button>
</body>
Upvotes: 1