How to pass value in select method in AngularJS - javascript

I have one problem in AngularJS. How to pass list value in html select method
Here is my code,
app.js
$scope.subcategory = function() {
var query = "SELECT unit FROM Length;";
$cordovaSQLite.execute(db, query).then(function(res) {
if (res.rows.length > 0) {
var message = "SELECTED -> " + res.rows.item(1).unit;
$scope.list = message;
}
});
}
index.html
<select ng-change="subcategory()" ng-options="x.list for x in subcategory"></select>

You can use function param's to make this work or $scope. For example, parsing subcategory.id (I don't know if id attributes does exists for you) to subselect categories by categoryId. You should also define a model by using ng-model.
View
<select ng-options="x.list for x in subcategory"
ng-model="selectedItem"
ng-change="subcategory()">
</select>
Controller
$scope.subcategory = function() {
//you can also access categoryId with
var query = "SELECT unit FROM Length WHERE id = "+ $scope.selectedItem.id+";";
$cordovaSQLite.execute(db, query).then(function(res) {
if(res.rows.length > 0) {
var message = "SELECTED -> " + res.rows.item(1).unit ;
$scope.list=message;
}
});
}

<select ng-options="x.list for x in subcategory" ng-model="selectedItem" ng-change="subcategory()"></select>
You can have access to the selected option fron inside the subcategory() function like this:
$scope.subcategory= function() {
//use the selectedItem as you like
console.log($scope.selectedItem.id);
}

In your ng-options you are making use of subcategory whereas in your JS, there is no variable named with subcategory but it's a method.
One cannot simply refer the method, unless it returns the list.
What you actually need is a variable, that contains the object list, that can be looped in the select to get the drop-downs.
Moreover, on using ng-change, you are not passing any id. A better way to do, is to bind the select with a ng-model, on change, you can have a watch on this variable.
You should modify your code somewhat like the following:
HTML:
<select ng-model="someObject.model" ng-options="x.list for x in subcategory"></select>
JS:
$scope.subcategory = ['list:'[{ 'obj1': 'var1' }, { 'obj2': 'var2' }, { 'obj3': 'var3' }]];

Related

How can I access a selected option's displayed value from a directive on the select element

My markup looks something like this
<select ng-model="search.parameters.selectedOptionId" ng-options="lookup.id as lookup.lookupValue for lookup in lookups.options" custom-attribute-directive>
<option value="" selected>All</option>
</select>
From the customAttributeDirective, I need to access the selected option value that is displayed in the dropdown (i.e. lookup.lookupValue). I've tried accessing the $viewValue on the ngModel, but it is set to the lookup.id (which I assume is the fault of the way ng-options is set up). I cannot modify the implementation of the markup due to the circumstances that I am implementing the directive against, so the problem must be solved there.
Bind the lookup.lookupValue for display and lookup.lookupValue for backend Id too. In that case you will get display text with ng-model
<select ng-model="search.parameters.selectedOptionId" ng-options="lookup.lookupValue as lookup.lookupValue for lookup in lookups.options" custom-attribute-directive>
<option value="" selected>All</option>
Found my answer. It turns out directives can access the dom directly.
link: function (scope, element, attrs, controller) {
scope.getViewValue = function () {
if (angular.isDefined(scope.overrideTagDisplay)) {
return scope.overrideTagDisplay;
}
else if (element[0].nodeName == "SELECT") {
return element.children()[element[0].selectedIndex].text;
}
else {
return ngModel.$viewValue;
}
}
scope.initialize()
}
EDIT: I found later that this method has the issue that if javascript modifies the model value somewhere else in the code and then this piece immediately runs, it does not pick up the new value because the DOM hasn't updated (this includes on page load and initial setting). I ended up passing the list of lookups into the directive as well and got around the lack of standardization in those lookups by having an optional "comparator key" that would defaultly look something like
var comparitorKey = { id: "id", lookupValue: "lookupValue"};
which is then utilized like this
var id = ngModel.$modelValue;
var filtered = scope.lookupList.filter(function (lookup) { return lookup[scope.comparitorKey.id] == id });
return filtered.length > 0 ? filtered[0][scope.comparitorKey.lookupValue] : null;
the idea being that someone could pass in an alternative like
var comparitorKey = {id: "userId", lookupValue: "userName" };

Get selected index from select list

I have a select like this:
<select class="form-control" ng-change="filtro(selected)" ng-init="Catalogos[0]" ng-model="selected" ng-options="item.Nombre for item in Catalogos"></select>
I wan to get select index value, I try to use:
$scope.selected
But I get params from the database instead of the index of the selected list. How can I get that Index? Regards
I try as maddockst comment:
$scope.filtro = function (item) {
$scope.Catalogos.indexOf(item);
}
But when I use it I get other values instead of index
There is how I have now:
HTML
<select class="form-control" ng-change="filtro(selected)" ng-init="Catalogos[0]" ng-model="selected" ng-options="Catalogos as item.Nombre for item in Catalogos"></select>
JS
function editar() {
$scope.filtro = function (item) {
alert($scope.Catalogos.indexOf(item));
console.log(index);
}
($("#tabla_catalogos tr.selected").hasClass("selected"));
{
var table = $('#tabla_catalogos').DataTable();
var row = table.rows('.selected').data();
var id = table.cell(row[0], 1).data();
//Toma el id referente a la columna seleccionada
$state.go("root.detalleregistros", { codigo: row[0].Codigo, nombre: row[0].Nombre, catalogoid: row[0].ID, catalogoselected: $scope.filtro });
}
}
But I always get -1 into alert
Inside filtro, you could get the index of the selected item in the Catalogos array using the following code:
Change the filtro function to:
$scope.filtro = function(item) {
var index = $scope.Catalogos.indexOf(item);
}
SO in this scenario if you go into dev tools, I assume chrome and go to your console tab. Type $scope.selected, it will give you the object definition and from there you'll see your selected index value.
It will have to be something like $scope.selected[0].value

How to `update` new value choosing from `select box` on click save button?

How to update new value choosing from select box on click save button.
I am using ng-click function like this in my JS function for update button:
$scope.updateDealDetail = function updateDealDetail (){
$scope.showEditView = !$scope.showEditView;
$scope.dealDetail.decisionMakerDetail.email = $scope.selectedid;
}
My function for edit button:
$scope.editUserDetail = function editUserDetail(){
$scope.showEditView = !$scope.showEditView;
$scope.showSubmitView = !$scope.showSubmitView;
deal.getIdData($scope.accountDetail. accountUsers[0].role,$scope.accountDetail.id).then(function successCb(data){
$scope.editIdOptionsData=data;
$scope.selectedid = $scope.editIdOptionsData[0].email;
});
};
and my HTML for bitton click is like this :
<select ng-model="selectedid" class="form-control">
<option ng-selected="selectedid" ng-repeat="eiod in editIdOptionsData" value="{{eiod.email}}">{{eiod.email}}
<button ng-click="updateDealDetail(eoid.email)" ng-disabled="dealDataSaveButtonDisabled">Update</button>
I am trying to this through ng-repeat because of by using ng-options my data through API is now showing in the box. But My data which is on first index is only getting set. What to do to set the a default value for the selection box and by selection any value, onclick need to update that value.
Don't use ngRepeat to render options, this is your problem. Correct code would be:
<select class="form-control"
ng-model="selectedid"
ng-options="eiod.email as eiod.email for eiod in editIdOptionsData">
</select>
Best practice to use ng-options, ng-model and ng-change on the <select> element
Online demo - https://plnkr.co/edit/Gaa8sMgerRv6chio4iYa?p=preview
html
<select
ng-model="selectedItem"
ng-change="onSelectedItemChanged()"
ng-options="item as item.email for item in items"></select>
js
app.controller('MainCtrl', function($scope) {
$scope.items = [{
email: 'asd1#asd.com'
}, {
email: 'asd2#asd.com'
}];
$scope.selectedItem = $scope.items[0];
$scope.onSelectedItemChanged = function() {
alert('you changed it to ' + $scope.selectedItem.email);
}
});

ng option initial value select

I have a dynamic combo box. I want to initialise the value of all combo boxes like this the image below is from adding static values like this
$scope.newObject ={ 0 : "N/P" ,1 : "N/P",2 : "N/P",3 : "N/P"}
so I tried to make for on each item on the list in this code below:
$scope.inifonction = ["N/P","N/A","OK","KO"];
//this is the option inside the combobox
$scope.displaydata = function(index) {
$scope.id = index;
$http.get("/fonctions?id=" + $scope.id).success(function(data) {
$scope.list = data;
for(i=0;i<$scope.list.length;i++)
{
$scope.tab = $scope.list[i].idfonction
//this to get the id of the list in a tab
console.log($scope.tab)
//[1,6,5,3] exemple of data in the console
$scope.newObject ={ tab : "N/P"}
}
});
but I didn't work and it looked like this:
and here's my HTML
<select ng-model="newObject[l.idfonction]" ng-options=" fct for fct in inifonction " class="form-control">
when I insert the data am getting this as a result of that ng-model
Object {1: "N/A", 2: "OK", 3: "N/A", 4: "N/P", tab: "N/P"}
Add this line to every dropdown option in the view:
<option value = "">N/P</option>
UPDATE:
I can see that you have an array specific for the initial values. You could use that to set the value as:
<option value = "">{{inifonction[0]}}</option> //This prints N/P
More, you could set to a scope and use it as :
$scope.tab = "N/P";
<option value = "">{{tab}}</option>
this fixed my issue i hope it helps you all
<select ng-init="newObject[l.idfonction] = inifonction[0] " ng-model="newObject[l.idfonction]" ng-options=" fct for fct in inifonction " class="form-control">

jquery variable doesn't change on update

This my problem's semplification. I want to append some text after an input field (on update of the same field), only when the value of a select element is IT.
That's the fields:
<select id="billing_country">
<option value="FR">FR</option>
<option value="IT">IT</option>
</select>
<input type="text" id="woocommerce_cf_piva">
this is the script:
jQuery(document).ready(function () {
var $country_select = jQuery('#billing_country');
// When country change
$country_select.change(function () {
var $country = jQuery('#billing_country option:selected');
$country.each(function() {
FieldCheck(jQuery(this).val());
})
});
function FieldCheck($country) {
var $element = jQuery('#woocommerce_cf_piva');
if ($country == 'IT') {
$element.change(function () {
$element.after($country);
});
}
}
});
You can see this also on jsFiddle
Why it append country name also if i select FR?
It's difficult to understand what you're trying to do with your code.
You want the text input to change its value only if the select box has "IT" selected?
Why are you setting a change handler on the text input?
Why iterate through a select box's options if it's a single select? Just set the text input with the selected option's value, e.g.,
$(function() {
var $billingCountry = $('#billing_country');
$billingCountry.change(function() {
var $country = $('#billing_country option:selected');
fieldCheck($country.val());
});
function fieldCheck(country) {
var $element = $('#woocommerce_cf_piva');
if ($country !== 'IT') {
return;
}
$element.val(country);
}
});
https://jsfiddle.net/davelnewton/w5deffvk/
Edits
Naming conventions changed to reflect typical JS
Non-constructor function names start with lower-case
Non-JQ element vars don't get a leading $
Country value used as guard clause rather than nesting logic
This code is trivial, but nesting can make things harder to reason about
I would add a span and put the text in there so on subsequent change you can fix it:
<select id="billing_country">
<option value="FR">FR</option>
<option value="IT">IT</option>
</select>
<input type="text" id="woocommerce_cf_piva" /><span id="afterit"></span>
Note that this is still pretty verbose:
jQuery(document).ready(function() {
var $country_select = jQuery('#billing_country');
var $element = jQuery('#woocommerce_cf_piva');
// When country change
$country_select.on('change', function() {
var $country = jQuery(this).find('option:selected')[0].value;
var d = ($country == 'IT') ? $country : "";
$element.data('selectedcountry', d);
});
$element.on('change', function() {
var ct = $(this).data('selectedcountry');
//as you have it: $(this).after(ct);// append
// put it in the span to remove/blank out on subsequent changes
$('#afterit').text(ct);
});
});
Here is the total less-verbose version:
$('#woocommerce_cf_piva').on('change', function() {
var v = $('#billing_country').find('option:selected')[0].value;
$('#afterit').text((v == 'IT') ? v : "");
});
You have two problems:
input tag does not have onchange event; you should use onkeydown instead;
you should assign events before if conditions.
If I understand the problem correctly, you want to update input field with the value entered only when drop down selection is "IT". If that is the case, you need to watch input field event and invoke FieldCheck function from with in input field events.

Categories