Reputation: 3798
I have an application where the user is presented with a list of dropdowns. Each dropdown has the same list of options. The user can add a new dropdown or remove one. See screenshot below.
I want to maintain what the user has selected as a simple list of values selected. For Example, for the above screenshot, I want to have the selection stored in the $scope
somewhere as
["homepage", "keyword", "location", "original_priority"]
Is this possible with AngularJS i.e. the user removes and adds dropdowns and angular automatically updates the list of selected values?
What I have tried so far
var ClassifierController = function($scope, $http) {
$scope.selected_classifiers = ['homepage', 'keyword', 'location', 'original_priority'];
/* Calling a service to get a list of values for the dropdowns */
$http.get('/rest/classifiers').then(function(resp) {
$scope.classifiers = resp.data;
});
$scope.add = function() {
console.log("Add");
// Checking if none is already in the list
var index = $scope.selected_classifiers.indexOf("none");
if (index > -1) {
alert("Cannot add. An unspecified grouper is already available at index " + (index+1));
}
else {
$scope.selected_classifiers.push("none");
}
}
$scope.remove = function(selection) {
console.log("Remove " + selection);
var index = $scope.selected_classifiers.indexOf(selection);
if (index > -1) {
$scope.selected_classifiers.splice(index, 1);
}
}
}
Then in the html
<div ng-controller="ClassifierController">
<ol>
<li ng-repeat="selection in selected_classifiers">
<select>{{selection}}>
<option ng-repeat="classifier in classifiers" value="{{classifier.value}}" ng-selected="classifier.value==selection">{{classifier.name}}</option>
</select> <button title="Remove" ng-click="remove(selection)">X</ux-button>
</li>
<li><button title="Add new grouper" ng-click="add()">Add</ux-button></li>
</ol>
</div>
The setup above works to present a good initial setup. There removes work, but the update of an existing dropdown OR update of a newly added dropdown does not work.
Upvotes: 0
Views: 258
Reputation: 49590
As with anything Angular, first define what your ViewModel looks like.
For example, if you want to have a list of select
names and their values, define the list to be like so:
$scope.selected_classifiers = [{name: "homepage", val: ""}, ...];
selected_classifiers
will hold/initialize the values of each selection, and also keep what selections you actually have.
Then, in the View, iterate over this list and create <selects>
:
<div ng-repeat="selection in selected_classifiers">
<select ng-model="selection.val"
ng-options="classifier for classifier in classifiers">
<option value="">{{selection.name}}</option>
</select>
<button title="Remove" ng-click="remove(selection)">X</button>
</div>
<button title="Add new grouper" ng-click="add()">Add</button>
Upvotes: 1