Reputation: 4201
I have a following confusion with ng-options. I have build a dropdown from array located into my controller. Here is my html code:
<div ng-app>
<div ng-controller="testCtrl">
<select multiple="multiple" ng-model="first" ng-options="c.name for c in listObj">
</select>
<select multiple="multiple" ng-model="second">
</select>
<hr/>
{{first}}
</div>
</div>
and this is my JavaScript:
function testCtrl($scope) {
$scope.listObj = [{name: "x", content: [1,2,3]},
{name: "y", content: [4,5,6]}];
}
And this is working jsFiddle:
http://jsfiddle.net/zono/rkBUL/10/
When user choose element from left select (with selected CTRL) I want the right select to be filled with corespondign content property. Eg:
When user select x to the left will be 1,2,3. When add y to the left will be 1,2,3,4,5,6. When deselect x - 4,5,6.
Best regards.
Upvotes: 2
Views: 66
Reputation: 3664
If you don't want to rely on a $watch
as suggested by @package, you can employ a helper function in your controller to unpack each individual value of content
, for each selected item in listObj
, into an array for the ng-options
of your second <select>
.
$scope.contents = function(arr) {
var values = [];
if (angular.isDefined(arr)) {
arr.forEach(function(v) {
values = values.concat(v.content);
});
}
return values;
};
And then:
ng-options="c for c in contents(first)"
Here's a demonstration JSFiddle.
Upvotes: 1
Reputation: 4801
You have to $watch
first
, and when it changes, read content of all selected values into a new array, let's call it firstContent
. The second select
would show items from firstContent
. Here's code from updated fiddle:
<select multiple="multiple" ng-model="first" ng-options="c.name for c in listObj">
</select>
<select multiple="multiple" ng-model="second" ng-options="element for element in firstContent">
</select>
$scope.$watch('first', function(value) {
if (!value) {
return;
}
var firstContent = [];
for (var i = 0; i < value.length; i++) {
firstContent = firstContent.concat(value[i].content);
}
$scope.firstContent = firstContent;
});
Upvotes: 1