how to get selected value on button click in angularjs? - javascript

How to get selected value in angulajs when clicked on the button, im using the following code please suggest me?
<div class="form-inline">
<div class="form-group">
<select class="form-control" data-ng-model="selectedTimeZone">
<option data-ng-repeat-start="(key, value) in timeZoneData.countries" data-ng-bind="value.name"></option>
<option data-ng-repeat-end="" data-ng-repeat="tz in value.timezones" data-ng-bind="' - ' + tz"></option>
</select>
</div>
<div class="form-group">
<input id="btnAddTimeZone" type="button" value="Add Time Zone" class="btn btn-default" data-ng-click="populateTimeZone(selectedTimeZone)"/>
</div>
</div>
in Controller--
$scope.populateTimeZone = function (world_timezones) {
};
Json data--
{
"countries": {
"US": {
"id": "US",
"name": "United States",
"timezones": [
"America/New_York",
"America/Detroit",
]
},
"CA": {
"id": "CA",
"name": "Canada",
"timezones": [
"America/St_Johns",
"America/Halifax",
]
},
"IN": {
"id": "IN",
"name": "India",
"timezones": [
"Asia/Kolkata"
]
},
}
}
But im getting empty string.

From the AngularJS docs:
To bind the model to a non-string value, you can use one of the following strategies:
the ngOptions directive (select)
the ngValue directive, which allows arbitrary expressions to be option values (Example)
model $parsers / $formatters to convert the string value (Example)
https://docs.angularjs.org/api/ng/directive/select
Option 1: Add ng-value
All you need to do is add an ng-value to your options and it should work. You also might want to add a ng-disabled="true" to your group headers so that it prevents the user from selecting "India" and not an actually timezone.
<option ng-repeat-start="(key, value) in timezones.countries" ng-bind="value.name" ng-disabled="true"></option>
<option ng-repeat-end="" ng-repeat="tz in value.timezones" ng-bind="' - ' + tz" ng-value="tz"></option>
Plunkr: https://next.plnkr.co/edit/l5H87H8k7Af5XIqH?open=lib%2Fscript.js&deferRun=1
Option 2: ng-options with group by
Here's a possible solution using ng-options on the select. You can still achieve a groupBy functionality grouping your timezones by country name.
HTML
<form>
<label>Timezone: </label>
<select class="form-control" ng-model="selectedTimezone" ng-options="tz.timezone group by tz.country for tz in timezones"></select>
</form>
<button class="btn btn-secondary" ng-click="populateTimeZone()">Add Timezone</button>
JavaScript
function MainCtrl($scope, MainService) {
$scope.selectedTimezone = undefined;
$scope.timezones = [];
MainService.loadTimezones().then(function(timezoneData){
$scope.timezones = Object.values(timezoneData.countries).flatMap(c => {
return c.timezones.map(tz => {
return {id: c.id, name: c.name, timezone: tz};
});
});
});
$scope.populateTimeZone = function(){
console.log('selectedTimezone', $scope.selectedTimezone);
};
}
Plunkr: https://next.plnkr.co/edit/Y4AVNU9X6MUAzckz?open=lib%2Fscript.js&deferRun=1

Related

Dropdown binding issue with track by

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)">

How to select default drop-down option in select list in Angular JS

I have the following select option :
<select ng-model="class_name" name="class_name" class="form-control">
<option ng-repeat="t in MemberClass" value="{{t}}">{{t.class_name}}</option>
</select>
I want to set default option MemberClass[0] to select option. I tried the following code but not working.
The JSON data is coming from Webservice...
//To fetch Member Class
$http.get('http://192.168.1.6:8080/apartment//member/class/list').then(function(response) {
$scope.MemberClass = response.data.list;
$scope.class_name = $scope.MemberClass[0]; // Not working
});
Member class JSON data is :
[
{
"class_id": 1,
"class_name": "Owner",
"class_details": "DCE"
},
{
"class_id": 7,
"class_name": "Staff "
},
{
"class_id": 10
"class_name": "Vendor"
}
]
Plunker sample : https://plnkr.co/edit/vVcrmOREkcVBBM2Ynhgv?p=preview
(Am getting error if I not select any option...)
You can utilize ng-options for this. It is the preferred way most of the times. Like this:
<select ng-model="class_name" ng-options="t as t.class_name for t in MemberClass">
</select>
Now, since you have $scope.class_name assigned as default value, it will be selected already.
working example
Use ng-init. Try like below.
<!DOCTYPE html>
<html ng-app="myApp" ng-controller="Ctrl">
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div class="form-group">
<label class="control-label col-md-3">Member Class </label>
<div class="col-md-4">
<select ng-model="class_name"
ng-init=" class_name = MemberClass[0]" name="class_name" ng-options="t as t.sub_class_name for t in MemberClass">
</select>
<p>Selected Value: {{class_name}} <p>
</div>
</div>
<button type="submit" ng-click="alertdata()">Save</button>
<script>
angular.module('myApp', [])
.controller('Ctrl', function($scope) {
var MemberClass;
$scope.MemberClass = [{
"sub_class_id": 1,
"sub_class_name": "Primary"
},
{
"sub_class_id": 2,
"sub_class_name": "Secondary "
},
{
"sub_class_id": 3,
"sub_class_name": "Dependent "
},
{
"sub_class_id": 4,
"sub_class_name": "Sub Member"
},
{
"sub_class_id": 5,
"sub_class_name": "None"
}
]
// $scope.class_name = $scope.MemberClass[0];
$scope.alertdata = function() {
$scope.class_name = "{}";
var parameter;
parameter = {
"member": {
"first_name": "first_name",
"role": [{
"role_id": 4
}],
"associated": "associated",
"class0": [JSON.parse($scope.class_name)],
"contect": [{
"intercom": "intercom"
}],
"individualdetails": [{
"gender": "gender"
}]
},
"address": [{
"street_address_1": "street_address_1"
}]
}
console.log(JSON.stringify(parameter));
};
});
</script>
</body>
</html>
You should definitly use ng-options for this
<select ng-model="class_name" ng-options="t as t.class_name for t in MemberClass">
</select>
To set a default, either set the $scope.class_name to a value of the MemberClass array or you can add an empty option tag as below which will be selected when the $scope.class_name is null
<select ng-model="class_name" ng-options="t as t.class_name for t in MemberClass">
<option value="">Select value</option>
</select>

AngularJS Select with ng-options binding to object not property

I am trying to bind a select list to ng-model state abbreviation value.. for instance "AK" for Alaska. The initial selection doesn't work apparently because the ng-model is set to a string instead of an object. I've looked all over and there are all other people that have this issue but I haven't found a solution that works.
my controller has the following code
$scope.states =
[
{
"name": "Alabama",
"abbreviation": "AL"
},
{
"name": "Alaska",
"abbreviation": "AK"
},
{
"name": "Arizona",
"abbreviation": "AZ"
}];
//I want the model to be the abbreviation string
$scope.state = "AK";
Here is the markup
<select class="form-control m-b" data-placeholder="Select Location"
required="" ng-model="state"
ng-options="state as state.name for state in states track by state.abbreviation">
</select>
<p>Selected State {{state}}!</p>
Here is a plnkr that shows shat I'm talking about
https://plnkr.co/edit/IzDY4GrOxJSaMV2MMP30
You can use
$scope.state.abbreviation
to get the abrevation of the state object that's selected.
plkr solution
OR
you could change the ng-options to
ng-options="state.abbreviation as state.name for state in states track by state.abbreviation"

Angular ngRepeat multiple select fields without displaying already selected data through ng-options

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

ng-repeat not working when given a dynamic index in an array

I have this array in $scope.types (example data) :
[
{
"id": 1,
"description": "Cat",
"property_type": [
{
"id": 1,
"description": "Nickname",
},
{
"id": 2,
"description": "Age",
},
{
"id": 3,
"description": "Color",
}
]
}
]
I want to populate a ng-repeat with the properties of the type. Here's what I did :
<div ng-repeat="property in types[parseInt($('#select_type').val())].property_type">
{{property.description}}
</div>
This code doesn't show anything. However, if I replace $('#select_type').val() with 0, which is the offset of the object in the array, it works. What I don't understand is that if I look in the console what's the value of $('#select_type').val(), I get "0"... so it should work, unless there's something I don't get right with Angular (which is probably the case here).
If it can help, here's my select :
<select ng-options="type.id as type.description for type in types" ng-model="current_data.object_type_id" id="select_type">
<!-- Generated by ng-options, not hardcoded -->
<option value="0" selected="selected">Cat</option>
<option value="1">Dog</option>
</select>
Have any idea?
Try to use the following code:
<div ng-repeat="property in current_data.property_type">
{{property.description}}
</div>
<select ng-options="type.description for type in types" ng-model="current_data" id="select_type">
<option value="">select</option>
</select>
Try this on your ng-repeat
<div ng-repeat="property in types[current_data.object_type_id].property_type">
{{property_type.description}}
</div>

Categories

Resources