I'm trying to remove options from drop downs based on the selections made in other drop downs.
For instance, on page load, I have one drop down, and a button which allows the creation of another drop down.
code for my operation:
<div class="form-inline" ng-repeat="setting in sensor.settings">
<select class="form-control" ng-model="setting.port" ng-options="item.name group by item.type for item in ports track by item.name">
<option value="">-- Module Port --</option>
</select>
</div>
<a href ng-click="newItem($event, sensor.settings)">New Port</a>
Expected Result:
If only one drop down exists, a user can select any option in it and no additional logic needs to be executed.
However, if the "new port" button is clicked, it'll create additional drop downs with the same options as the first, second, etc...
What I'm looking to do is remove the options which are selected in any of the drop downs from those which the option wasn't selected from to prevent duplicate selections.
So for instance, if I have 3 drop downs, and the available selections to all drop downs are D1, D2, and D3; the user selects D1 for the first, which removes option D1 from drop downs 2 & 3. D2 is selected in the second, which removes D2 from drop down 1 & 3, leaving drop down 3 with a single selection of D3.
Here's a link to my code:
I have forked your plunker, and I think I have something that should work for you here.
The important part is that I changed ng-options to use a filtered list of ports, based on the index you're currently looking at. (I changed the ng-repeat to also track the index):
<div class="form-inline" ng-repeat="(index, setting) in sensor.settings">
<select class="form-control" ng-model="setting.port" ng-options="item.name group by item.type for item in filteredPorts(index) track by item.name" ng-change="updateAll(index)">
<option value="">-- Module Port --</option>
</select>
</div>
I then implemented filteredPorts as a function that takes an index and filters out all other selected ports and returns only those as the possible options:
$scope.filteredPorts = function(index) {
// Filter out anything that's currently selected elsewhere
var currentSelections = [];
$scope.sensor.settings.forEach(function(value, idx) {
if (index !== idx) { currentSelections.push(value.port); } // if statement enforces "elsewhere"
});
Note that I also defined an array diff method, used in the above code:
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
}; // from http://stackoverflow.com/questions/1187518/javascript-array-difference
return $scope.ports.diff(currentSelections);
}
I also changed the newItem function to just create a new item and not do any filtering:
$scope.newItem = function($event, sensorSetting) {
$scope.sensor.settings.push({
port: '',
room: '',
device: ''
});
$event.preventDefault();
}
Finally, just in case, I added an ng-click handler that deals with any duplicates, but that shouldn't be possible so can probably be ignored.
To explain why it didn't work in the first place and what the main difference here is, you were changing the $scope variable from which all of the <select>s were pulling -- you want to change it for each one individually, which I accomplish here by passing in the index variable to a function.
Related
As a simple test I'm passing 2 lists to a javascript function, only the list without a multiple attribute populates, the second list does get the "select one or more items" option but not 1,2,3 and only after I lose focus from list2. Can anyone tell me how I can repopulate the multiselect?
<select id="lstTest"></select>
<select id="lstTest2" multiple="multiple"></select>
function TestList(obj) {
var x = $(obj);
x.append('<option value="">Select one or more items</option>');
x.append('<option value="1">1</option>');
x.append('<option value="2">2</option>');
x.append('<option value="3">3</option>');
}
Empty Lists
List 1 after javascript call
List 2 after javascript call
Turns out the select is referencing custom js to turn it into a checkbox list as a way of selecting the items instead of highlighting. I need to treat it as a checkbox list and not just a list of options, which I'm still not sure how to do, I need to clear and add new checkboxes.
A view of my AngularJS app makes heavy use of ng-repeat directive. It is done like this:
<div ng-repeat="branches in company">
<p>{{branches.name}}</p>
<p>{{branches.location}}</p>
<div>
<select ng-model="branches.officeInformationType">
<option ng-repeat="offices in branches">{{offices.type}}</option>
</select>
<select ng-model="branches.officeInformationMeters">
<option ng-repeat="offices in branches">{{offices.meters}}</option>
</select>
<select ng-model="branches.officeInformationColor">
<option ng-repeat="offices in branches">{{offices.color}}</option>
</select>
</div>
</div>
The fact is, the second ng-repeat and and the others after it (offices in branches) are actually the same everytime, so it wouldn't need to be recalculated for every branch. It would need to be binded to the row it belonges to, for saving it later, so the branches.officeInformation model should still be watched by angular, but I would like to make the whole program more performant.
I am using angular-ui-router and when I change the view between my "Choose your office" view and any other, the lag is tremendous, almost at a minute of wait time when you leave the "Choose your office" page. It renders fast enough, 2 seconds for the whole rendering, but when I leave the page it takes a ton of time to change to the other view.
Any ideas, taking into consideration that the ng-model binding "branches.officeInformation.." is of importance?
EDIT: I have tried remove the nested ng-repeats and for each ng-repeat that I removed, the transition between states got faster and faster. When I removed all the nested ng-repeats the transition became instantaneous, hence why I believe it has to do with the ng-repeats.
The ng-repeats are tracked by $index and where possible I used :: for one time binding.
Thanks.
We can lazy load a dropdown's options right before the user interacts with it.
First, we initialize each dropdown with only the selected option, so you can see it when the dropdown is closed.
Then we attach an ng-focus directive to each dropdown. When our callback fires we can:
fully populate the options for that dropdown
remove all but the selected option from the previously active dropdown
I wasn't entirely sure of the structure of your data (it looks like some arrays have additional properties on them). So I chose to create "view model" objects that represent the UI. You can adapt this to your own structure.
Controller:
// Set up some test office options (null for no selection)
var allOffices = [null];
for (var i = 0; i < 50; i++) {
allOffices.push(i);
}
// activeDropdown holds the dropdown that is currently populated with the full list
// of options. All other dropdowns are only populated with the selected option so
// that it shows when the dropdown is closed.
var activeDropdown;
$scope.company = [
// Branch 1
[
// These objects represent each dropdown
{
// Just the selected option until the user interacts with it
options: ["0"],
selected: "0"
}, {
// Just the selected option until the user interacts with it
options: ["1"],
selected: "1"
}, {
// Just the selected option until the user interacts with it
options: [null],
selected: null
}
],
// Branch 2
[
// These objects represent each dropdown
{
// Just the selected option until the user interacts with it
options: ["2"],
selected: "2"
}, {
// Just the selected option until the user interacts with it
options: ["3"],
selected: "3"
}, {
// Just the selected option until the user interacts with it
options: [null],
selected: null
}
]
];
// When the user interacts with a dropdown:
// - fully populate the array of options for that dropdown
// - remove all but the selected option from the previously active dropdown's
// options so that it still shows when the dropdown is closed
$scope.loadOffices = function (dropdown) {
if (activeDropdown === dropdown) {
return;
}
dropdown.options = allOffices;
if (activeDropdown) {
activeDropdown.options = [activeDropdown.selected];
}
activeDropdown = dropdown;
};
Template:
<div ng-repeat="branch in company">
<div ng-repeat="dropdown in branch">
Selected: {{ dropdown.selected }}
<select ng-focus="loadOffices(dropdown)" ng-model="dropdown.selected">
<option ng-repeat="o in dropdown.options">{{ o }}</option>
</select>
</div>
</div>
Note that ng-focus was the only directive I needed to apply to each dropdown when I tested this. But you may need to add ng-keydown, ng-mouseover, ng-click, or others to get it to work in all scenarios including mobile.
I also noticed a potential styling issue. When you focus on a dropdown, we load all of the options for that dropdown. This may cause the width of the dropdown to change, so if you can set the same width for all of them you should be good.
If the number of options in each dropdown is huge, we may be able to optimize even further by writing some custom directives that interact and allow the actual DOM element options to be shared. But I suspect we won't have to go that far for this example.
Have you tried 'track by $index' ? it will reduce angular watches overhead.
something like that:
div ng-repeat="branches in company track by $index">
<p>{{branches.name}}</p>
<p>{{branches.location}}</p>
<div>
<select ng-model="branches.officeInformationType">
<option ng-repeat="offices in branches track by $index">{{offices.type}}</option>
</select>
<select ng-model="branches.officeInformationMeters">
<option ng-repeat="offices in branches track by $index">{{offices.meters}}</option>
</select>
<select ng-model="branches.officeInformationColor">
<option ng-repeat="offices in branches track by $index">{{offices.color}}</option>
</select>
</div>
</div>
First and foremost, thanks to those that helped me find the answer.
The problem was that I nested too many ng-repeats with too many event handlers attached to each repeated element. ng-models, ng-changes and ng-clicks were really heavy, but the number of elements was also out of control.
I solved this by using a single select without any nested ng-repeats, this select (and the options) are in a modal view, so a different controller. From that controller I return the select results, having only one select for all the elements in the page. When the data is returned from the modal, I use it from the main controller of the view.
Thanks again.
I have a dynamic list to display on dropdown. But always the first element of the list should be selected by default on gui and later on user can select any other.
When I am trying to display the first element of the list in my drop down, that element repeated in the list and if user select any other element then that element is being repeated. Below is my code.
html code:
<select class="form-control" name="settingTabs" id="settingTabs" ng-model="mData.selectedTabName" ng-change="selectTab()" ng-init="mData.selectedTabName = mData.tabList[0].settingTabName" ng-options="settingTabs.settingTabName for settingTabs in mData.tabList">
<option value="">{{mData.selectedTab}}</option>
</select>
js code:
$scope.selectTab = function(){
var x = $scope.mData.tabList.indexOf($scope.mData.selectedTabName);
$scope.mData.selectedTab = $scope.mData.tabList[x].settingTabName;
}
Need help here so I can have only the list to display in dropdown and by default first element should be selected displayed from that list.
I myself got an answer so thought of posting this too. Since angular provide default option for drop down, so make that ng-if="false" will work here.
<option value="" ng-if="false">{{mData.selectedTab}}</option>
I have dropdownlist whose value is filled using the value of the other drop down. The problem here is that i need to bind the value of the second when the value of the first changes. I need to do it from the javascript.
Only thing i need to do is remove and add the select options in the second dropdown as the first dropdown changes.
How can i do this?
Thanks in advance.
Not too sure exactly what you want with the limited information provided but here is a solution that I think you are looking for:
HTML:
<select id="primary">
<option value="one">One</option>
<option value="two">Two</option>
</select>
<select id="secondary"></select>
jQuery:
var opts = {
'one':['a','b','c'],
'two':['d','e','f']
};
$('#primary').change(function(){
var select = [];
$.each(opts[this.value], function(k, v){
select.push('<option>'+ v +'</option>');
});
$('#secondary').html(select.join(''));
});
Demo: http://jsfiddle.net/28TQZ/
$("#dropdownlist1").change(function () {
var selected = $("#dropdownlist1 option:selected");
//clear
$("#dropdownlist2").html("");
$("#dropdownlist2").append($("<option/>").text(selected.text()).val(selected.val()));
})
Create all the drop downs you need, but only add options to the first one. The next ones only have a "default" value.
On selecting the first drop down, you use jQuery to get the values for the second drop down, based on the value selected in the first drop down:
$.post('ajax/aj_populate2nddropdown.php', $("#firstdropdown").val(), function(result) {
$('div.placedaround2nddropdown').html(result);
});
The file ajax/aj_populate2nddropdown.php collects the values of the second drop down, and returns them, inserted as options into the dropdown.
One simple way to do it is to just have a main dropdown and a bunch of secondary dropdowns that start hidden. when you choose something from the first, then you unhide the related second one
Try this If you are trying at client side
Replace your controls with asp.net server controls
I have a set of drop down lists (8 in all). All drop downs have the same set of drop down options available to them. However the business requirement is to make sure that the user cannot select the same option more than once.
Looking at the problem, at first it appears simple but it's rapidly becoming lots of code. However it seems like a relatively common problem. Does anyone know of a solution, have any tips on how to do this without writing reams of Javascript. Some sort of reusable jquery plugin might be handy for this too. Does one exist?
One issue is that when a select item is chosen, it then becomes unavailable to the other select lists. The item is removed from the other select drop downs. When it becomes available again (a drop down changes) it needs to be inserted at the correct point in the list (the drop down options have an order). This is the bit where my solution has started to get quite complex.
Personally, the way I'd implement it is to have a "master" drop down containing all possible options, simply for the purpose of caching. These options are then replicated in each of the "slave" drop downs. Whenever any slave drop down is changed, they're all re-populated again to ensure that no two drop downs can share the same selected value.
For the purpose of demonstration, I've only worked with 3 drop down lists in the code below, but it should scale up pretty easily. Just add mode drop downs and make sure they contain the attribute class="slave".
Also, if you want any of the options to be immune from being removed, so that it's possible to exist in all of your slave drop downs (such as the default option in the code below), just add the attribute class="immune" to the option tag in the master drop down.
<script type="text/javascript">
// document - on load
$(document).ready(function() {
// initially populate all the drop downs
PopulateAllDropDowns();
// populate all drop downs on each subsequent change
$('select.slave').change(function(){
PopulateAllDropDowns();
});
});
function PopulateAllDropDowns()
{
// populate all the slave drop downs
$('select.slave').each(function(index){
PopulateDropDown($(this).attr('id'));
});
}
function PopulateDropDown(id)
{
// preserve the selected value
var selectedValue = $('#'+id).val();
// clear current contents
$('#'+id).html('');
// attempt to add each option from the master drop down
$('select#ddlTemplate').children('option').each(function(index){
// scope-safe var
var masterOptionValue = $(this).val();
// check if option is in use in another slave drop down, unless it's immune
var optionInUse = false;
if (!$(this).hasClass("immune"))
{
$('select.slave option:selected').each(function(index){
if (masterOptionValue == $(this).val() )
optionInUse = true;
});
}
// if it's not in use, add it to this slave drop down
if (!optionInUse)
{
// create new option
var newOption = $('<option></option>').val($(this).val()).html($(this).text());
// ensure selected value is preserved, if applicable
if (selectedValue == $(this).val())
newOption.attr('selected', 'selected')
// add the option
$('#'+id).append(newOption);
}
});
}
</script>
<form>
<!-- master drop down -->
<select id="ddlTemplate" class="master" style="display:none">
<option value="" class="immune">Select ...</option>
<option value="a">Option A</option>
<option value="b">Option B</option>
<option value="c">Option C</option>
<option value="d">Option D</option>
<option value="e">Option E</option>
</select>
<!-- slave drop downs -->
<select id="ddlOne" class="slave"></select>
<select id="ddlTwo" class="slave"></select>
<select id="ddlThree" class="slave"></select>
</form>
Hope that helps.
The simplest way to do what you want is binding a function in the select event from dropdown list that filter content from all other dropdowns and remove or disable the options with value already selected.
To keep the order from your list, cache the options list in array, then you can remove and add in the right position, or remove all options and re-add the current possible options.
If you want re-select the cached already chosen options, and you don't lose anything.