how to select few json values in drop down in angularjs - javascript

i am getting a data from json file and the values using in dropdown but i dont want to use all values,I want to select only three values in my dropdown.

You can filter the list at the time of feeding it to the dropdown.
<select ng-model="toType" class="form-control" required ng-change="ConvertCurrency()"
ng-options="k for (k, v) in (rates | 'yourfilter') track by v"></select>
[UPDATE]
I tried to access the API, and found out that res.data.rates is an object and not an array.
So if you only have to show these 3 values, the easy approach would be to create a new array in controller:
var ratesToDisplay = [];
ratesToDisplay.push({rate:'USD', value: res.data.rates.USD});
ratesToDisplay.push({rate:'EUR', value: res.data.rates.EUR});
ratesToDisplay.push({rate:'CAD', value: res.data.rates.CAD});
and feed this new filtered array to your dropdown.
<select ng-model="selectedRate" ng-options="rate.value as rate.rate for rate in ratesToDisplay">
<option value="" disabled>Please Select</option>
</select>
I hope this helps.
For 2nd part of your problem
You can implement the ng-change() method and call the API from that method. Ex:
function onDDChange(){
$http.get('http://api.fixer.io/latest?' + $scope.fromType.label)
.then(function(res) { \\logic for success call back
\\ call convert currency method from here.
});
}
HTML:
<select ng-model="fromType" class="form-control" required
ng-change="onDDChange()" ng-options="f as f.label for f in rates">

I have written this code and it is working for me
angular.module('CurrencyConv', [' ']).controller('ConvertCtrl', ['$scope', '$http', function($scope, $http) {
$scope.rates = [];
$scope.toType = {};
$scope.fromType = {};
$http.get('http://api.fixer.io/latest?base').then(function(res) {
$scope.fromValue = 1;
$scope.ConvertCurrency();
var i = 0;
angular.forEach(res.data.rates, function(value, key) {
if (key == "USD" || key == "EUR" || key == "CAD") {
$scope.rates.push({ value: value, label: key });
// $scope.toType = $scope.rates.CAD;
// $scope.fromType = $scope.rates.USD;
}
i++;
});
});
<select ng-model="fromType" class="form-control" required ng-change="ConvertCurrency()" ng-options="f as f.label for f in rates">

Related

how do i make the option selected in append jquery in foreach

How can I make the option selected according to the value I get from value[0] in the loop?
$.each(data, function(key, value) {
$("#cektubuh").append(
`<tr>
<td>
<select name="duration_type[]" class="form-control" required>
// here I want to add the selected option according to $ {value [0]}
<option value="Semester">Semester</option>
<option value="Month">Month</option>
</select>
</td>
</tr>`
});
});
As you have not provided an example of the data, there is no way to know what values are being used here or how they compare. Here is a basic example based on what you have provided.
$.each(data, function(k, v) {
var row = $("<tr>").appendTo($("#cektubuh"));
var cell = $("<td>").appendTo(row);
var sel = $("<select>", {
name: "duration_type[]",
class: "form-control"
}).prop("required", true).appendTo(cell);
$("<option>", {
value: v[0]
}).html(v[0]).prop("selected", true).appendTo(sel);
$("<option>", {
value: "Semester"
}).html("Semester").appendTo(sel);
$("<option>", {
value: "Month"
}).html("Month").appendTo(sel);
});
If it's more complex or has multiple elements, please provide an example of the structure so that a more complete answer can be shown.
if you have value which belongs to options list and you want to show as selected option
just do this.
var value = 'some value';
$('name="duration_type[]"').val(value);
it will show that value as selected.

How to set a particular value selected when data is coming from an API

I have a dropdown list:-
<label>User Code:</label>
<select ng-options="c as c.User for c in userList"
ng-model="selectedUser" id="search3">
</select>
The data in this dropdown is coming from an API. My directive code:-
scope.getAllPeriodicities = function(){
scope.userList = [];
ApiServices.getAllPeriodicities().then(function (response) {
scope.userList = response.data;
});
}
scope.getAllPeriodicities();
There is an User Code:-SS1234. I want this user to be selected whenever the page loads. I am thinking of using selected attribute but not sure how to use it on the fetched data.
scope.getAllPeriodicities = function(){
scope.userList = [];
ApiServices.getAllPeriodicities().then(function (response) {
scope.userList = response.data;
scope.selectedUser = "SS1234";
});
}
scope.getAllPeriodicities();
simply asign, scope.selectedUser="SS1234" user you want.
scope.userList = response.data;
scope.selectedUser = scope.userList[0].User /* here i choose 0th index of user. you can change as you want */
Set your default value to the ng-model by using ng-init or ng-value
<select ng-options="c as c.User for c in userList" ng-model="selectedUser"
id="search3" ng-value={{selectedUser = 'SS1234'}}></select>
//or
<select ng-options="c as c.User for c in userList" ng-model="selectedUser"
id="search3" ng-init="selectedUser = 'SS1234'"></select>
In your controller add,
$scope.selectedUser = 'SS1234';

Set Selected Option In Dropdown in AngularJS onload

In Angularjs, I have a DropDown:
<select ng-model="category" ng-change="categoryChanged(category)" class="form-control"
data-ng-options="category as category.name for category in categories">
<option value="">Select Category</option>
</select>
And I have a controller:
app.controller('searchBoxController', ['$scope', '$location', '$routeParams', 'categoryService', function ($scope, $location, $routeParams, categoryService) {
categoryService.getParentCategory().$promise.then(
function (model) {
$scope.categories = model;
$scope.category.id = $routeParams.categoryId;// Which is coming as "1"
},
function (error) {
});
$scope.categoryChanged = function (category) {
alert(category.id);
};
}]);
$routeParams.categoryId is coming as "1" but still it is not setting the selected option in the dropdown.
Your categories variable is an array of objects, while you set the ng-model to an object with only an id. Because it is a whole new object, angular doesn't see it as a match of the category in your array, and won't select the correct one.
The solution is to set the $scope.category to the matching object of the array instead of creating a new one:
var id = $routeParams.categoryId;
// Find the category object with the given id and set it as the selected category
for (var i = 0; i < $scope.categories.length; i++){
if ($scope.categories[i].id == id) {
$scope.category = $scope.categories[i];
}
}
You have to change ng-model directive when promise operation is end.
<select ng-model="category" ng-change="categoryChanged(category)" class="form-control" data-ng-options="category as category.name for category in categories">
<option value="">Select Category</option>
</select>
Suppose you have var id = $routeParams.categoryId and its value is 2 for example. You have to find category from categories where category.id is 2. For this, the simpliest method is to use a filter method.
$scope.category = $scope.categories.filter(function(item){
return item.id==$scope.id;
})[0];
Please take a look to working fiddle

Populate dropdown list dynamically in AngularJS

I'm trying to generate dynamic form based on the key of document fields and using ng-if attribute in AngularJS.
Ex:
- If field name is "name|string" then populate textfield
- If field name is "name|select" then populate dropdownlist
- If field name is "name|datepicker" then populate datepicker
Following is the code:
<div class="form-group" ng-repeat="(index, formVal) in providerModelData" ng-if="!$first">
<label>{{mySplit(index,0) | uppercase}}</label>
<div ng-if="!mySplit(index,1)">
<input type="text" class="form-control" ng-model="providerModelData[index]">
</div>
<div ng-if="mySplit(index,1) == 'datepicker'">
<input type="text" class="form-control" ng-model="providerModelData[index]">
</div>
<div ng-if="mySplit(index,1) == 'select'">
<select class="form-control" ng-init="getDropdownData(index,colName)" ng-options="dropdown._id for dropdown in dropdownData[colName]">
<option value="">Select</option>
</select>
</div>
</div>
controller:
$scope.mySplit = function(string, nb) {
var array = string.split('|');
return array[nb];
}
textfields are working fine and populating data but I'm facing issue while populating dropdown fields.
Example: I've two dropdown fields in my mongodb document i.e. city|select and state|select
I'm trying to use ng-options to call function by passing index and colName (document name) to populate dropdownlist but its not working.
Following is the code:
$scope.dropdownData = {};
$scope.getDropdownData = function (query, colName) {
$http.get('/getdropdowndata/', {
params: {
query: query,
colName: colName
}
}).success(function (response) {
$scope.dropdownData[colName] = response;
});
};
Express:
router.route('/').get(function (req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query.query);
db.collection(query.colName).aggregate([{
"$group":{
"_id":"$"+query.query
}
}],function (err, docs) {
console.log(docs);
res.json(docs);
});
});
Initially I tried calling function in ng-repeat but it was going into infine loop. Then later I tried ng-init options but it only calls or initialize once which is not working in my case. Here I need to call function dynamically and based on that I want to populate dropdown for different fields.
Any help would be appreciated.
Your view is completely messed up as far I see it you are missing
ng-model
for your select input.
Your JSON is improper its missing , before {'id_':'Arizona'}
Try to get response in your controller and push it to array and make use of that array in your View :
$scope.getDropdownData=function(query, colName){
$http.get('/getdropdowndata/', {
params: {
query: query,
colName:colName
}
}).success(function (response) {
var returnArray = [];
alert(JSON.stringify(response));
angular.ForEach(response,function(option){
//parse response and push it to returnArray
returnArray.push(option);
});
return returnArray;
});
}
View :
<div class="form-group">
<select class="form-control" ng-model="selection" ng-options="dropdown._id for dropdown in getDropDownData()">
<option value="">Select</option>
</select>
</div>
Here is the link to Codepen
.
Consider the following solution:
In your controller, set up a variable for the dropdown data:
$scope.dropdownData = {};
Then change your getDropdownData function to:
$scope.getDropdownData=function(query, colName){
$http.get('/getdropdowndata/', {
params: {
query: query,
colName:colName
}
}).success(function (response) {
alert(JSON.stringify(response));
$scope.dropdownData[colName] = response; // This will put data into our html file
});
}
And the HTML for your dropdown case should be:
<div ng-if="mySplit(index,1) == 'select'">
<select class="form-control" ng-init="getDropdownData(index,colName)" ng-options="dropdown._id for dropdown in dropdownData[colName]">
<option value="">Select</option>
</select>
</div>
I used the notorious ngInit to make the call from getting data for the server. Perhaps there's a better way that I didn't consider. But in any case, the idea is to make the call to the server, and save the data in a way that you can fetch it easily from the view.
Edit
I don't know why, but for some reason this solution doesn't work with ng-options. It does, however, work when using it like this:
<select class="form-control" ng-init="getDropdownData(index,colName)">
<option value="">Select</option>
<option ng-repeat="dropdown in dropdownData[colName]" value="dropdown._id">{{dropdown._id}}</option>
</select>
See a simple example here.
Finally I solved it myself. Thanks #Rishab777 and #yarons for guiding me.
Here's the view code:
<div ng-if="mySplit(index, 1) == 'select'">
<select class="form-control">
<option value="">Select</option>
<option ng-model="providerModelData[index]" ng-selected="providerModelData[index]" ng-repeat="dropdown in dropdownData[index]" value="{{dropdown._id}}">{{dropdown._id}}</option>
</select>
</div>
and controller:
$scope.showModal = false;
$scope.toggleModal = function (colId, colName) {
$http.get('/collectiondata/' + colId + '/collectionName/' + colName).success(function (response) {
$scope.colName = colName;
$scope.colId = colId;
for (var key in response) {
if (response.hasOwnProperty(key)) {
if ($scope.mySplit(key, 1) === 'select') {
$scope.getDropdownData(key, colName);
}
}
}
$scope.providerModelData = response;
$scope.showModal = !$scope.showModal;
});
};
$scope.dropdownData = {};
$scope.getDropdownData = function (query, colName) {
$http.get('/getdropdowndata/', {
params: {
query: query,
colName: colName
}
}).success(function (response) {
$scope.dropdownData[query] = response;
});
};
Now the issue is ng-selected="providerModelData[index]" is not working and its showing last item as selected only.

AngularJS set values of multi-select dropdown

I have a multi select dropdown that functions as appropriate when setting values, but once set, I need to display what has been selected in an update form. My values are stored in a DB (SharePoint) accessible over REST. Here is an example REST output with multiple IDs of my array:
"CatId": [
18,
80,
84
],
Here is my select function, including retrieving the variable from REST:
var currentCatValue = results.CatId;
$scope.categoryValues = [];
appCatList.query(function (categorydata) {
var categoryValues = categorydata.value; // Data is within an object of "value", so this pushes the server side array into the $scope array
// Foreach type, push values into types array
angular.forEach(categoryValues, function (categoryvalue, categorykey) {
$scope.categoryValues.push({
label: categoryvalue.Title,
value: categoryvalue.ID,
});
})
var currentDetailIndex = $scope.categoryValues.map(function (e) { return e.value; }).indexOf(currentCatValue);
$scope.vm.selectedCategory = $scope.categoryValues[currentDetailIndex];
});
Here is my HTML:
<select class="form-control" id="Event_Cat" data-ng-model="vm.selectedCategory"
data-ng-options="opt as opt.label for opt in categoryValues | orderBy:'label'" required>
<option style="display:none" value="">Select a Category</option>
</select>
EDIT: Using id (inspired by yvesmancera) in ng-model would greatly reduce the complexity - You don't need to pre-process your options and input array anymore, just plug it in and done!
<select multiple ng-model="currentCatValue" ng-options="opt.ID as opt.Title for opt in categoryValues">
$scope.currentCatValue = currentCatValue;
$scope.categoryValues = categoryValues;
Note: normally we would pre-populate ng-options into an array to preserve the order of the options, if the original data is an object. But since you use orderBy, you can use the object directly as ng-options.
fiddle
Outdated:
You need to point to the same object in ng-options for them to get selected on load.
$scope.categoryValues = [];
$scope.vm.selectedCategory = [];
angular.forEach(categoryValues, function (categoryvalue, categorykey) {
var category = {
label: categoryvalue.Title,
value: categoryvalue.ID,
}
$scope.categoryValues.push(category);
if (currentCatValue.indexOf(parseInt(category.value)) != -1) {
$scope.vm.selectedCategory.push(category);
}
});
Try changing your ng-options to something like:
<select class="form-control" id="Event_Cat" data-ng-model="vm.selectedCategory" data-ng-options="opt.id as opt.label for opt in categoryValues | orderBy:'label'" required>
<option style="display:none" value="">Select a Category</option>
</select>
And make this line change in your controller:
$scope.vm.selectedCategory = $scope.categoryValues[currentDetailIndex].id;
Edit for multiple selection:
<select class="form-control" id="Event_Cat" data-ng-model="selectedCategoriesIds" data-ng-options="opt.id as opt.label for opt in categoryValues | orderBy:'label'" required multiple>
<option style="display:none" value="">Select a Category</option>
</select>
In your controller, add the items you want selected to $scope.selectedCategoriesIds e.g.:
$scope.selectedCategoriesIds = [];
$scope.selectedCategoriesIds.push('18');
$scope.selectedCategoriesIds.push('80');

Categories