I have two drop down fields where the second one is dependent on the selection in the first.
The data for the first drop down comes from one data set. It lists the number associated with an account ng-repeat="option in acctList": 1, 4 and 7.
I want to go to a different data set, find the account numbers that match, and then show the Customers that are related to that account. (account 1 has customers 1-2, account 4 has customers 3-4, and account 7 has customers 5-7). The second drop down should show nothing (blank) when nothing has been selected in the first.
Here is my plunker with the two drop downs: http://plnkr.co/edit/jDitkge1rx6GJzkdElJO?p=preview
Here is my controller:
angular.module("app", [])
.controller("MainCtrl", function($scope) {
$scope.test = "This is a test";
$scope.defnum = 1;
$scope.acct_info = [
{
"Req": "MUST",
"DefCom": "1"
},
{
"Req": "NoMUST",
"DefCom": "5"
},
{
"Req": "MUST",
"DefCom": "4"
},
{
"Req": "MUST",
"DefCom": "7"
}
];
$scope.cust_info = [
{
"Customer": "1",
"Com": "1"
},
{
"Customer": "2",
"Com": "1"
},
{
"Customer": "3",
"Com": "4"
},
{
"Customer": "4",
"DefCom": "4"
},
{
"Customer": "5",
"DefCom": "7"
},
{
"Customer": "6",
"DefCom": "7"
},
{
"Customer": "7",
"DefCom": "7"
}
];
});
I added ng-repeat="option in cust_info | filter:{ Com : filter.DefCom }" to try to filter the second based on this SO answer: Filter ng-options from ng-options selection
But it's not working.
I've tried using ng-change, but I think there should be an easier way, like a filter or track by. I'm wondering also if I should change from ng-repeat to ng-option. Anyone have insight on an easy way to do this?
Use ng-if in your second <option> tag, may it is, whatever you want
<select>
<option ng-selected="defnum == option.DefCom" ng-repeat="option in acct_info | filter:{Req:'MUST'}:true">
{{ option.DefCom }}
</option>
</select>
<select>
<option ng-if="option.DefCom" ng-selected="" ng-repeat="option in cust_info">
{{ option.Customer}}
</option>
</select>
Related
I am getting problem while binding my dropdown value with associative array.
Problem is with track by so like when I don't add track by to my dropdown then I have my binding with dropdown and when I add track by then O am unable to auto select dropdown value.
I want to use track by with ng-options so that angular js doesn't add
$$hashKey and leverage performance benefit associated with track by.
I am not getting why this behaviour is happening.
Note: I only want to bind name of choices like Pizza or burger for each of my $scope.items and not whole object.
Update: As I understand and with so much trying with current data structure of my $scope.items it is not working with ng-options and I want to use ng-options with track by to avoid generating hash key by Angular js. I also tried ng-change as suggested by #MarcinMalinowski but I am getting key as undefined.
So what should be my data structure of $scope.items so that when I need to access any item from my $scope.items? I can access it without doing loop (like we access items from associative array) like how I can access now with correct data structure and using ngoptions only with track by.
var app = angular.module("myApp", []);
app.controller("MyController", function($scope) {
$scope.items = [
{
"title": "1",
"myChoice" :"",
"choices": {
"pizza": {
"type": 1,
"arg": "abc",
"$$hashKey": "object:417"
},
"burger": {
"type": 1,
"arg": "pqr",
"$$hashKey": "object:418"
}
}
},
{
"title": "2",
"myChoice" :"",
"choices": {
"pizza": {
"type": 1,
"arg": "abc",
"$$hashKey": "object:417"
},
"burger": {
"type": 1,
"arg": "pqr",
"$$hashKey": "object:418"
}
}
}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul ng-app="myApp" ng-controller="MyController">
<div ng-repeat="data in items">
<div>{{data.title}}
</div>
<select ng-model="data.myChoice"
ng-options="key as key for (key , value) in data.choices track by $index"><option value="">Select Connection</option></select>
</div>
</ul>
The problems in your code are:
1) track by $index is not supported by ngOptions, it will result the value of the option to be undefined(in your case it will be an $index of ngRepeat);
2) track by doesn't work well with object data-sources (it is supposed to be used with array data-sources), from the docs:
trackexpr: Used when working with an array of objects. The result of
this expression will be used to identify the objects in the array.
Of course, you can use ngRepeat to generate option elements, but personally, I would prefer using ngOptions without track by due to the benefits it has over ngRepeat.
UPDATE: Here is the code that illustrates how you can change your initial data-source and use track by to pre-select an option in case the model is an object. But even in the first example console.log() shows that $$hashKey was not added to choices object.
var app = angular.module("myApp", []);
app.controller("MyController", ['$scope', '$timeout', function($scope, $timeout) {
$scope.items = [
{
"title": "1",
"myChoice" :"burger",
"choices": {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
}
},
{
"title": "2",
"myChoice" :"",
"choices": {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
}
}
];
$scope.itemsTransformed = angular.copy($scope.items).map(function(item){
delete item.myChoice;
item.choices = Object.keys(item.choices).map(function(choice){
item.choices[choice].name = choice;
return item.choices[choice];
});
return item;
});
//select an option like an object, not a string
$scope.itemsTransformed[1].myChoice = $scope.itemsTransformed[1].choices[0];
$timeout(function() {
//changes a prop in opts array - options are not-re-rendered in the DOM
//the same option is still selected
$scope.itemsTransformed[1].choices[0].arg = "xyz";
}, 3000);
$scope.selectionChanged =function(key, items){
console.log(items); //as we can see $$hashKey wasn't added to choices props
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul ng-app="myApp" ng-controller="MyController">
<p>Without track by:</p>
<div ng-repeat="data in items track by data.title">
<div>{{data.title}} - {{data.myChoice}}</div>
<select ng-model="data.myChoice"
ng-options="key as key for (key , value) in data.choices"
ng-change="selectionChanged(key, items)">
<option value="">Select Connection</option>
</select>
</div>
<hr/>
<p>Using track by name to pre-select an option:</p>
<div ng-repeat="data in itemsTransformed track by data.title">
<div>{{data.title}} - {{data.myChoice}}</div>
<select ng-model="data.myChoice"
ng-options="choice as choice.name for choice in data.choices track by choice.name"
ng-change="selectionChanged(key, itemsTransformed)">
<option value="">Select Connection</option>
</select>
</div>
</ul>
UPDATE 2: A simple example that shows us the fact $$hashKey property is not added to the objects when using ngOptions without track by:
var app = angular.module("myApp", []);
app.controller("MyController", ['$scope', '$timeout', function ($scope, $timeout) {
$scope.items = {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
};
$scope.selectionChanged = function (key, items) {
console.log($scope.items);
};
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<hr/>
<p>Example without track by:</p>
<select ng-model="myChoice"
ng-options="key as key for (key , value) in items"
ng-change="selectionChanged(myChoice, items)">
<option value="">Select Connection</option>
</select>
<hr/>
{{myChoice}}
</div>
UPDATE 3: Final result below (that work with angularjs versions < 1.4, for 1.4+ I would recommend changing the data structure as $scope.itemsTransformed in the first code snippet):
angular.module("myApp", [])
.controller("MyController", ['$scope', function ($scope) {
$scope.items = [
{
"title": "1",
"myChoice": "burger",
"choices": {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
}
},
{
"title": "2",
"myChoice": "",
"choices": {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
}
}
];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<div ng-repeat="data in items track by data.title">
<div>{{data.title}} {{data.myChoice}}</div>
<select ng-model="data.myChoice"
ng-options="key as key for (key , value) in data.choices">
<option value="">Select Connection</option>
</select>
</div>
</div>
ngOptions doesn't create new scope like ngRepeat directive per item therefore you don't need to take care about to get rid of $$hashKey
I would use ng-repeat to iterate on <option> (suppose you don't create long lists):
<select ng-model="data.myChoice">
<option value="">Select Connection</option>
<option ng-repeat="(key , value) in data.choices track by key" ng-value="key" title="{{key}}"
>{{key}}</option>
</select>
Working Demo Fiddle
Take look on this issue: github.com/angular/angular.js/issues/6564 - ng-options track by and select as are not compatible
I believe this issue still exists so suggest you to use ngRepeat with track by instead. For small list there is no performance penalty
ngOptions attribute can be used to dynamically generate a list of elements for the element using the array or object
ngModel watches the model by reference, not value. This is important to know when binding the select to a model that is an object or a collection.
1.If you set the model to an object that is equal to an object in your collection, ngOptions won't be able to set the selection, because the objects are not identical. So by default, you should always reference the item in your collection for preselections, e.g.: $scope.selected = $scope.collection[3]
ngOptions will track the identity of the item not by reference, but by the result of the track by expression. For example, if your collection items have an id property, you would track by item.id.
For Example :
$scope.items = [
{
"title": "1",
"myChoice" :"",
"choices": {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
}
},
{
"title": "2",
"myChoice" :"",
"choices": {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
}
}
];
From the above 2nd point, track the identity of the item not by reference.
Add keyName of key in the object and track by keyName or track by arg , type.
Track by arg or type :
<select ng-model="data.myChoice"
ng-options="choice as choice.arg for choice in data.choices track by choice.arg">
<option value="">Select Connection</option>
</select>
Or add keyName inside the choice object
$scope.items = $scope.items.filter(function(item){
delete item.myChoice;
item.choices = Object.keys(item.choices).map(function(choice){
item.choices[choice].keyName = choice;
return item.choices[choice];
});
return item;
});
HTML Code:
<div ng-controller="MyCtrl">
<ul>
<div ng-repeat="data in items">
<select ng-model="data.selected"
ng-options="choice as choice.keyName for choice in data.choices track by choice.keyName"
ng-change="selection(data.selected)">
<option value="">Select</option>
</select>
</div>
</ul>
</div>
Demo Link Example
You need to add ng-change and pass/use your ng-model value there to get any property you wish.
<select class="form-control pickupaddress ng-pristine ng-valid ng-touched m-r-sm m-t-n-xs" ng-model="item.pickup_address" tabindex="0" aria-invalid="false" ng-options="add._id as add.nick_name for add in addPerFood[item.food._id] | unique:'nick_name'" ng-change="dropDownSelect(item.pickup_address,allCarts,item,$index)">
I have the following JSON (test JSON as how it comes from the server):
$scope.allCategoriesAndSubcategories = {
"category" : {
"categoryname" : "pasteleria",
"subcategory" : [
{"subcategoryname" : "pastel tradicional", "subcategoryid" : "1"},
{"subcategoryname" : "pastel con fondant", "subcategoryid" : "2"}
]
},
"category" : {
"categoryname" : "eventos",
"subcategory" : [
{"subcategoryname" : "boda", "subcategoryid" : "1"},
{"subcategoryname" : "cumpleanos", "subcategoryid" : "2"}
]
}
};
Then on the select in the HTML I do the following:
<div input-field>
<select material-select
ng-model="picture.category1" required>
<optgroup ng-repeat="category in allCategoriesAndSubcategories" label="{{category.categoryname}}">
<option value="{{category.subcategory.subcategoryid}}">{{category.subcategory.subcategoryname}}</option>
</optgroup>
</select>
<label>CategorÃa #2</label>
</div>
When I console.log() I get the actual object so it's not undefined, however the select is not populating. Should I do something else to populate it? I'm new to angularJS and I can't find an example similar to this one
The HTML is invalid if you wish to create list of options
<div input-field>
<select material-select ng-model="picture.category1" required>
<optgroup ng-repeat="category in allCategoriesAndSubcategories" label="{{category.categoryname}}">
<option ng-repeat="subcategory in category.subcategory" value="{{subcategory.subcategoryid}}">{{subcategory.subcategoryname}}</option>
</optgroup>
</select>
<label>CategorÃa #2</label>
</div>
then after you select element the model picture.category1 should be populated
working plunker http://codepen.io/maurycyg/pen/PZpRRy
also your data should be formatted differently
$scope.allCategoriesAndSubcategories = [{
"categoryname": "pasteleria",
"subcategory": [{
"subcategoryname": "pastel tradicional",
"subcategoryid": "1"
}, {
"subcategoryname": "pastel con fondant",
"subcategoryid": "2"
}]
}, {
"categoryname": "eventos",
"subcategory": [{
"subcategoryname": "boda",
"subcategoryid": "1"
}, {
"subcategoryname": "cumpleanos",
"subcategoryid": "2"
}]
}];
});
I think that proble is here
<option value="{{category.subcategory.subcategoryid}}">
Subcategory is array, and i think that you should use new ng-repeat to make list of <option> tags
I'm giving following data input to select2
data = [{
"id": "all",
"text": "All",
"children": [{
"id": "item1",
"text": "item1"
}, {
"id": "item2",
"text": "item2"
}]
}];
and I'm initialising select2 as:
$(parent).select2({"data":data});
Now to select the value "item1", I did
$(parent).select2("val",["item1"]);
However instead of value "item1" value "all" is getting selected. How to select value item1?
To set the selected value using select2 you should use:
$(parent).val("item1").trigger("change");
From the release notes:
You should directly call .val on the underlying element instead. If you needed the second parameter (triggerChange), you should also
call .trigger("change") on the element.
$("select").val("1"); // instead of $("select").select2("val", "1");
JSFiddle where item1 is selected.
JS:
var data = [{
id: 'all',
text: 'All',
children: [{
id: 'item1',
text: 'item1'
}, {
id: 'item2',
text: 'item2'
}]
}];
$('.js-example-data-array').select2({data:data});
$('.js-example-data-array').select2('val',['item1']);
HTML:
<select class="js-example-data-array">
</select>
I tried to make this demo to show you that it works. The demo, uses the select tag as a selector for an empty and existing select element. Indeed, I don't know what are you meaning by parent:
<select>
</select>
<script>
data = [{
"id": "all",
"text": "All",
"children": [{
"id": "item1",
"text": "item1"
}, {
"id": "item2",
"text": "item2"
}]
}];
$('select').select2({
"data": data
});
$('select').select2("val", ["item2"]);
</script>
I'm not sure if you mean that the value "All" gets selected at start or if you want to select "item1" by code and it doesn't work. I find it strange that "All" gets selected as value since it should be treated as a category, even by adding
$(".select2-text").select2("val",["item1"]);
it won't select "All" for me. If i add
$(".select2-text").select2("val",["item2"]);
It will select "item2" for me (which means the method to select the item works, though it's not the best way, as stated in Lelio Faieta's Answer)
if i add
$(".select2-text").select2("val",["all"]);
it won't select "All" for me, it will just show me a blank select. So I think there must be an issue with your code because in a clean page there seems to be no way to select "All"
Can you show us the whole code, including the html of your page (at least the part relevant to the select). I have tried this (see plunker here: http://plnkr.co/edit/m6pFUt?p=preview )
<script>
$(document).ready(function() {
data = [{
"id": "all",
"text": "All",
"children": [{
"id": "item1",
"text": "item1"
}, {
"id": "item2",
"text": "item2"
}]
}];
$(".select2-text").select2({
"data": data
});
});
</script>
<select class="select2-text"></select>
And it starts with item1 selected, while "All" is treated as a category. So maybe it's just because something is wrong in your code/HTML.
What version of Select2 are you using? i'm using 2-4.0.0
So the overview of the problem; I am retrieving data from an api and creating a CRUD page for it. The data has a set of labels that the user can select.
Below is a code sample representing my problem. The labels selected by the user are represented by the user.labels relationship and the total available labels that can be selected are represented by user.parent.grandparent.labels.
I'm able to sync the selection. What I can't seem to figure out is how to get rid of options that have already been selected from the list of options on any other subsequent select field.
angular.module('app', [])
.controller('select', ['$scope', '$filter', '$location',
function($scope, $filter, $location) {
$scope.user = {
"parent": {
"grandparent": {
"labels": [{
"id": 28,
"name": "Label 1",
}, {
"id": 17,
"name": "Label 2",
}, {
"id": 39,
"name": "Label 3",
}, {
"id": 77,
"name": "Label 4"
}, {
"id": 100,
"name": "Label 5"
}]
}
},
"labels": [{
"id": 28,
"name": "Label 1",
"meta": {
"score": 3
}
}, {
"id": 17,
"name": "Label 2",
"meta": {
"score": 5
}
}]
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="select">
<div ng-repeat="label in user.labels track by $index">
<div class="form-field">
<span>Label</span>
<select ng-model="user.labels[$index]" ng-options="department.name for department
in user.parent.grandparent.labels track by department.id">
</select>
</div>
<div>
<span>Score</span>
<select ng-model="label.meta.score">
<option value="1">1 (lowest)</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5 (highest)</option>
</select>
</div>
</div>
<button ng-click="user.labels.push({})">Add Label</button>
</div>
You can use a filter function inside the ng-repeat to achieve this, here is a sample Codepen showing you how:
http://codepen.io/anon/pen/ZYveOo
You need to pass the filter in the repeat definition:
<select ng-model="user.labels[$index]" ng-options="department.name for department in user.parent.grandparent.labels | filter:removeSelected track by department.id ">
Which refers to this function on scope:
$scope.removeSelected = function(val){
return !_.find($scope.user.labels, function(label) {
return label.id === val.id;
});
};
Even then though I think you are missing one use case which is that you want to be able to have the currently selected label included in the options, by removing all selected options you are removing that ability.
Updated:
Ok then, so after giving this some thought I have come up with the following filter which could be optimised but does seem to work as expected:
.filter('duplicatesFilter', function() {
return function(items, index, selected) {
var res = [selected[index]];
_.forEach(items, function(item){
if(!_.find(selected, function(label) {
return label.id === item.id;
})){
res.push(item);
}
});
return res;
};
})
Use it like so:
<select ng-model="user.labels[$index]" ng-options="department.name for department in user.parent.grandparent.labels | duplicatesFilter:$index:user.labels track by department.id "></select>
This is something I have hit a few times and each time I've worked around it. I'll take a look later if I can find a custom filter that better solves the problem and if I can't I'll tidy up this code and release one; however this should be good to go for your use-case.
Working code-pen:
http://codepen.io/anon/pen/ZYveOo
I have a page on which I output a list of Cars. The results in this list are coming from a Json file.
This is an example of my Json:
[
{
"id": "1590",
"brand": "Peugeot",
"type": "508"
},
{
"id": "1591",
"brand": "Peugeot",
"type": "308"
},
{
"id": "1594",
"brand": "Honda",
"type": "Civic"
},
{
"id": "1605",
"brand": "Renault",
"type": "Clio"
},
{
"id": "1607",
"brand": "Renault",
"type": "Laguna"
}
]
I need to filter the results by e.g. Brand and Type. So I have two DropDown lists named 'selectedBrand' and 'selectedType'.
I used this markup to load the single Brands into the DropDown list:
<select id="brands" data-ng-model="selectedBrand" data-ng-options="car.brand for car in cars | unique:'brand' | orderBy:'brand'">
</select>
This works okay and gives me a DropDown list with the unique brands, like a DISTINCT SELECT.
Now I want the second DropDown list to be filtered when the first one has a selected value.
This is the markup I have for the second DropDown list:
<select id="type" data-ng-model="selectedType" data-ng-options="car.type for car in cars | filter:{brand:selectedBrand} | unique:'type' | orderBy:'type'">
</select>
But this is not working. It shows the complete list with types of every brand.
I guess I need some way to trigger it when the first DropDown list changes?
I pretty new to AngularJs, so any help would be appreciated.
I don't know if this is the best way to get those DISTINCT values out of the Json results. I only have this complete Json result set with all the data and that is what I have to work with.
Following the docs you'll need a ng-model-options="{ updateOn: 'your option here' }" to do this bind