Bind options value to ng-model in angularjs - javascript

I'm working on a project, and I need to bind the options value to object key's in such a manner that, on selecting an option, it gives 1, else other variables remain 0.
My HTML Code:-
<select required class="custom-select">
<option disabled>Select an option</option>
<option ng-model="PredictCtrl.detail.building_type_AP">Apartment</option>
<option ng-model="PredictCtrl.detail.building_type_GC">Independent House / Villa</option>
<option ng-model="PredictCtrl.detail.building_type_IF">Independent Floor / Builder's Floor</option>
<option ng-model="PredictCtrl.detail.building_type_IH">Gated Community Villa</option>
</select>
Variable to bind -
PredictCtrl.detail = {
building_type_AP: 0,
building_type_GC: 0,
building_type_IF: 0,
building_type_IH: 0
}
Generally, binding is done with select tag, which gives the value of the selected option, but I want in such a way that, when I click on Apartment option, it's bind variable PredictCtrl.detail.building_type_AP becomes 1, rest remains 0. Similarly, it does with other options.
I want to send the data as the same format through API.
So, please Help me out.
Sorry If I was not very clear with explaining or for any typo.
Thank you in advance.

You should take a look at the NgOptions directive which is the "angularjs" way of working with the select-tag.
It sould be able to fulfill your requirement as you will get the selected option in the SelectedOption object.
Here's an example
angular.module("app",[]).controller("myCtrl",function($scope){
$scope.details =
[
{name:"Apartment", value:1},
{name:"Independent House / Villa", value:2},
{name:"Independent Floor / Builder's Floor", value:3},
{name:"Gated Community Villa", value:4}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<select required class="custom-select" ng-options="item as item.name for item in details" ng-model="selectedOption">
</select>
<p>SelectedOption: {{selectedOption}}</p>
</div>

None of the answers at my time of writing actually present a functioning solution, so here's one.
Don't scatter ng-model directives across different option elements, it's unnecessary.
You can achieve what you want by using ng-options to enumerate all your choices, a single ng-model to keep track of the selected option, and ng-change to apply the values as you described (i.e. 1 on the selected key, 0 for everything else).
I've assumed you've got a requirement to keep the structure of detail as is. If it can be changed, then I'd recommend associating each labels with each it's respective building_type_ to keep things together.
See below.
angular
.module('app', [])
.controller('PredictCtrl', function () {
this.selectedDetail = null;
this.detail = {
building_type_AP: 0,
building_type_GC: 0,
building_type_IF: 0,
building_type_IH: 0,
};
this.labels = {
building_type_AP: 'Apartment',
building_type_GC: 'Independent House / Villa',
building_type_IF: 'Independent Floor / Builder\'s Floor',
building_type_IH: 'Gated Community Villa',
};
this.changeDetail = function () {
for (var key in this.detail) {
this.detail[key] = +(this.selectedDetail === key);
}
};
});
<script src="https://unpkg.com/angular#1.7.4/angular.min.js"></script>
<div ng-app="app" ng-controller="PredictCtrl as PredictCtrl">
<select
ng-model="PredictCtrl.selectedDetail"
ng-options="key as PredictCtrl.labels[key] for (key, value) in PredictCtrl.detail"
ng-change="PredictCtrl.changeDetail()"></select>
<pre>{{ PredictCtrl.detail | json }}</pre>
</div>

try like this:
in your controller:
$scope.details = [
{
name: "building_type_AP",
value: "Apartment",
state: false
},{
name: "building_type_GC",
value: "Independent House / Villa",
state: false
}/*add more here*/
];
$scope.setActive = function(detail){
detail.state = !detail.state;
}
in html template:
<select required class="custom-select">
<option disabled>Select an option</option>
<option ng-repeat="detail in details" ng-click="setActive(detail)">{{detail.value}}</option>
</select>
in the end just go through $scope.details and parse false to 0 and true to 1 OR just do this inside setActive function

Related

How to make a <select> tag in html only shows some data depending on another <select> tag using Vue.js

I'm displaying two <select> elements. The second <select> is disabled depending on the <option> selected on the first <select>. The problem is when I select an <option> on the first <select>, I want the data shown on the second <select> to be changed. For example, if I select District 1 on the first <select>, I want to see john and mary as options in the second <select>, but if I select District 2, I want josef and charles. Consider that I'm doing this on Laravel and using Vue.
I have done the first part using Vue, disabling the second <select> depending on what has been chosen on the first <select> (only third option on the first <select> will enable the second <select>):
https://jsfiddle.net/vowexafm/122/
Template:
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
<select #change="treat">
<option value="District1">District 1</option><!--disable 2nd select-->
<option value="District2">District 2</option><!--disable 2nd select-->
<option value="District3">District 3</option><!--enable 2nd select-->
</select>
<br><br>
<select :disabled="isDisabled">
<option>cds 1</option>
<option>cds 2</option>
<option>cds 3</option>
</select>
</div>
Script:
new Vue({
el:'#app',
data: {
isDisabled: true,
},
methods: {
treat: function(e) {
if (e.target.options.selectedIndex == 0 ||
e.target.options.selectedIndex == 1) {
return this.disable();
}
if (e.target.options.selectedIndex != 0 &&
e.target.options.selectedIndex != 1) {
return this.enable();
}
},
enable: function() {
return this.isDisabled = false; // enables second select
},
disable: function() {
return this.isDisabled = true; // disables second select
}
},
});
Now the solution I want,for example: if i'I select District 1 on the first , I want to see john and mary as options in the second , but if I select District 2, I want to see josef and charles on the second .
Populate data object from laravel to have the options for the second select in it and a value for the current selected index from the first select
data: {
secondSelect: [
['john', 'mary'],
['josef', 'charles']
],
currentIndex: 0
}
Define a computed property that returns the values for the second select depending on currentIndex
computed: {
persons () {
return this.secondSelect[parseInt(this.currentIndex)]
}
}
Generate the second select using the computed property persons and use v-model to capture currentIndex.
<div id="app">
<select #change="treat" v-model="selectedIndex">
<option value="0">District 1</option><!--diable-->
<option value="1">District 2</option><!--diable-->
<option value="2">District 3</option><!--unable-->
</select>
<br><br>
<select :disabled="isDisabled">
<option v-for="option in persons" :value="option">{{option}}</option>
</select>
</div>
now the solution I want,for example if i select 'District 1 'on the
first i want to see 'john' and 'mary' as options in the second , but
if I select 'District 2' i want to see 'josef' and 'charles' on the
second .
is that whats in your mind?
new Vue({
el:'#app',
data:{
district:'-1',
options:{
'District1':false,
'District2':false,
'District3':false
},
},
methods:{
getOptions(){
axios.get('https://jsonplaceholder.typicode.com/users',{district:this.district}).then(res=>
this.options[this.district]=res.data)
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
<select v-model="district" #change="getOptions()">
<option value="-1" selected disabled hidden>choose a district</option>
<option value="District1">District 1</option>
<option value="District2">District 2</option>
<option value="District3">District 3</option>
</select>
<br><br>
<select v-if="options[district]">
<option v-for="option in options[district]">{{option.name}}</option>
</select>
</div>
edit:
after your comment, i edited this answer so now its fetching the data from some api.
to fetch the options from a db, you first have to create an api for your app, and when the request comes out of your vue client side - the server will retrieve rows from the db, do some caculations based on the parameters you sent in the request, and bring back a json data array.
(i wont cover the server side now - thats completely off-topic. but you can easily google for 'laravel json response')
in this snippet, i used some example json api, just to show you how its done on the client side:
i use v-if to cause late- rendering of the second select. it will be rendered only after i get the options, via axios (a very common npm package used to make ajax requests in modern js frameworks).
im also registering an event listener to the change event of the first select - to make my ajax request and populate my options every time the disrict changes (i used a default option to avoid unneeded requests)

Angularjs Dropdown won't hold value after refresh

I have been working on this way too long trying to figure it out.
<select class="form-control"
ng-model="question.sel"
ng-change="updateDropDownQuestion(question,question.sel)">
<option ng-repeat="answer in question.answers" ng-disabled="answer.notAnOption" value="{{answer.acode}}">{{answer.name}}</option>
<option style="display:none" value="NONE">NONE</option>
</select>
Then in my js file:
$scope.updateDropDownQuestion = function(question, answer) {
reset(question.code)
$scope.formData["SOLE/SELECTED_QUESTION"] = question.code
$scope.formData["SOLE/SELECTED_ANSWER"] = answer
$scope.formData[question.code+"/"+answer] = true
var questions = $scope.product.questions
for(i=0; i <questions.length;i++){
if(questions[i].code == question.code){
questions[i].sel = answer
break;
}
}
$scope.refresh()
};
the $scope.refresh() is where it changes back. This renders the screen.
no matter what I do it seems to render the previous state and not the current state of the drop down. This is because I am repainting the screen after the drop down changes.
It seems as though the when the screen repaints it is taking the original value first.
Any thoughts on how I can get the value to "stick" once set?
Do I need to fire some event afterwards?
From Angular official site:
Note: ngModel compares by reference, not value. This is important when binding to an array of objects. You might find this helpful to set the default values of your drop down. See an example below.
angular.module('demoApp', []).controller('DemoController', function($scope) {
$scope.options = [
{ label: 'one', value: 1 },
{ label: 'two', value: 2 }
];
// Although this object has the same properties as the one in $scope.options,
// Angular considers them different because it compares based on reference
$scope.incorrectlySelected = { label: 'two', value: 2 };
// Here we are referencing the same object, so Angular inits the select box correctly
$scope.correctlySelected = $scope.options[1];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="demoApp">
<div ng-controller="DemoController">
<div>
<h2>Incorrect</h2>
<p>We might expect the select box to be initialized to "two," but it isn't because these are two different objects.</p>
<select ng-model="incorrectlySelected"
ng-options="opt as opt.label for opt in options">
</select>
The value selected is {{ incorrectlySelected.value }}.
</div>
<div>
<h2>Correct</h2>
<p>Here we are referencing the same object in <code>$scope.correctlySelected</code> as in <code>$scope.options</code>, so the select box is initialized correctly.</p>
<select ng-model="correctlySelected"
ng-options="opt as opt.label for opt in options">
</select>
The value selected is {{ correctlySelected.value }}.
</div>
</div>
</body>
Try using ng-options to render option elements.
Something along these lines:
<select class="form-control"
ng-model="question.sel"
ng-change="updateDropDownQuestion(question,question.sel)"
ng-options="answer.acode as answer.name in question.answers">
</select>
It also depends on what updateDropDownQuestion is doing, can you provide that?

Select default value at ng-options

I have this code and information:
$scope.options = [
{ id: 1, label: "My label" },
{ id: 2, label: "My label 2" }
];
$scope.selected = 2;
<select ng-options="opt.label for opt in options" ng-model="selected">
<option value="">Select one</option>
</select>
However, the options are created like this:
<select ng-options="opt.label for opt in options" ng-model="selected">
<option value="">Select one</option>
<option value="0">My label</option>
<option value="1">My label 2</option>
</select>
How can I set the selected option to My label 2? I know it can be done:
$scope.selected = $scope.options[1];
But my problem is that option is created in a directive, and at that moment I don't know 1) how many values has $scope.options, nor 2) what is the index of the selected option in database. The only thing I know is the id (which is in the object).
The html of my directive is something like this:
<select ng-switch-when="select" ng-model="form.model[element.model]" ng-options="{{element.rule}}"></select>
Where element.rule is:
rule: "role.role for role in element.options"
And element.options has the array with options, and form.model[element.model] has the id of the option selected.
How can I get the index of the element with ID X in the array $scope.options? I'm very sure that will give me the solution, but I don't know how to do it...
Just set the correct model value when initiating the controller. You can easily get the correct array value if you know the ID by using a filter:
$scope.selected = $filter('filter')($scope.options, {id: 2})[0];
The issue with your code as I see it is that the 'selected' value coming out of your database is the ID of the object selected and not the object itself. This is fine but because of that difference you can't simply set
$scope.selected = 2 //assuming 2 is the value coming from your database
because the value '2' does not exist in your option array. The Object with an ID of 2 does.
If you can always guarantee the options you have in the option array are from 1-n and in that order, you can accomplish this by simply using this instead:
$scope.options = [
{ id: 1, label: "My label" },
{ id: 2, label: "My label 2" }
];
var selectedIdFromDatabase = 2;
$scope.selected = $scope.options[selectedIdFromDatabase-1];
If you can't make that guarantee (and even if you can for now, it may not be a good idea to make that assumption in your code) you'll need iterate over the array of objects you have to identify the object with an ID of the selectedId from your database.
The answer to this question has a great write-up about the type of data-processing you'll need to do and a lot more information about javascript objects in general.

Can't set select value from my controller, Angular JS

From this example
I'm trying to set the select value from my controller and this doesn't work for me even when I set the id as explained in many questions here. The only difference is that I have a default value set with ng-init. How do I set the value from the controller?
DOM:
<select ng-model="storeorder" ng-init="storeorder = 0" ng-change="storeOrderChange(storeorder)">
<option value="0">-- All orders --</option>
<option ng-repeat="obj in orders" value="{{ obj.id }}">{{ obj.name }}</option>
</select>
JS inside a function:
$scope.orders = data;
$scope.storeorder = parseInt($scope.order); // Tried without parseInt also
console.log($scope.storeorder) returns the right value, but it doesn't set the right value in the browser DOM.
If you don't want to use ng-options(which is the right way) , you can try with
ng-selected : Working Demo : http://jsfiddle.net/nf2m0rr1/
Example :
<body ng-app ng-controller="OrderCtrl">
<div>Order is: {{storeorder}}</div>
<select ng-model="storeorder">
<option ng-selected="{{order.value == storeorder}}" ng-repeat="order in orders" value="{{order.value}}">{{order.displayName}}</option>
</select>
</body>
function OrderCtrl($scope) {
$scope.storeorder = 2;
$scope.orders = [{
value: '1',
displayName: 'Order One'
}, {
value: '2',
displayName: 'Order Two'
}]
}
Use ng-options:
<select ng-model="storeorder" ng-init="storeorder = 0" ng-change="storeOrderChange(storeorder)" ng-options="obj.id as obj.name for obj in orders">
ng-options solved 50% of the problem but I still needed to handle the default value in the DOM and change the ng-init option. This was really bugging me. Here's the complete solution which enabled me to not set anything from the controller:
<select ng-model="storeorder" ng-options="orderdata.id as orderdata.name for orderdata in orders" ng-init="storeorder = order == 0 ? 0 : order" ng-if="orders.length > 0" ng-change="storeOrderChange(storeorder)">
<option value="">-- All orders --</option>
</select>

AngularJS null value for select

I couldn't find an elegant way for setting null values with a <select> using AngularJS.
HTML :
<select ng-model="obj.selected">
<option value=null>Unknown</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
{{obj}}
JS :
$scope.obj ={"selected":null};
When the page is loaded, the first option is selected, which is good, and the output is {"selected":null}. When that first option is reselected after having switch to another one, the output becomes {"selected":"null"} (with the quotes), which is not what I would expect.
Running example :
http://plnkr.co/edit/WuJrBBGuHGqbKq6yL4La
I know that the markup <option value=null> is not correct. I also tried with <option value=""> but it corresponds to an empty String and not to null : the first option is therefore not selected and another option which disappears after the first selection is selected by default.
Any idea ?
This should work for you:
Controller:
function MyCntrl($scope) {
$scope.obj ={"selected":null};
$scope.objects = [{id: 1, value: "Yes"}, {id: 0, value: "No"}]
}
Template:
<div ng-controller="MyCntrl">
<select ng-model="obj.selected"
ng-options="value.id as value.value for value in objects">
<option value="">Unknown</option>
</select>
<br/>
{{obj}}
</div>
Working plnkr
You should use ng-options with select.
You can use the ngOptions directive on the select. According to the documentation:
Optionally, a single hard-coded <option> element, with the value set to an empty string, can be nested into the <select> element. This element will then represent the null or "not selected" option. See example below for demonstration.
<select ng-model="obj.selected" ng-options="key as label for (key, label) in ['No', 'Yes']">
<option value="">Unknown</option>
</select>
It's obviously a better idea to define the options list directly in the controller.
Try using ng-options instead of manually creating tags, as in this example, lightly-edited from the Angular docs:
http://plnkr.co/edit/DVXwlFR6MfcfYPNHScO5?p=preview
The operative parts here are lines 17, defining a 'colors' object, and the ng-options attributes iterating over those colors to create options.
If you REALLY want to use null, see below. You need to use ng-options and let Angular handle the mapping:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Color selector</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.8/angular.min.js"></script>
</head>
<body ng-app="">
<script>
function MyCntrl($scope) {
$scope.obj ={"selected":null};
$scope.objStates = [{key:"Unknown", value:null}, {key:"Yes", value:1}, {key:"No", value:0}]
$scope.$watch('obj.selected', function(newVal){
console.log(newVal);
})
}
</script>
<div ng-controller="MyCntrl">
<select ng-model="obj.selected" ng-options="state.value as state.key for state in objStates">
</select>
<br/>
{{obj}}
</div>
</body>
</html>
I ran into the same Problem but could not solve it via 'ng-options'. My solution is:
module.directive('modelToNull', [function () {
return {
scope: {
check: "&modelToNull"
},
require: 'ngModel',
link: function ($scope, element, attrs, ngModelController) {
ngModelController.$parsers.push(function (value) {
return value == null || $scope.check({value: value}) ? null : value;
});
}
};
}]);
You can use it like this:
<select ng-model="obj.selected" model-to-null="value == 'null'">
<option value="null">Unknown</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
Can you try to use parseInt on the value? For example, both "1" and "0" will equal their respective integer values. If you run the empty string through parseInt you can easily get NaN.
> parseInt("") = NaN
> parseInt("0") === 0
> parseInt("1") === 1
Without the possibility of using ng-options I present another fix.
I've been battling this a couple of months now, using solutions presented on this question and I don't know how nobody posted this:
<option value="null"></option>
This should work on Angular 1.6 and above for sure when you are using ng-repeat for options instead of ng-options.
It's not ideal but since we are used to work on legacy code this simple fix could save your day.
the only way you can achieve that is by using a onchange event and restoring the object as initialized any other attempt to set the selected to null will remove the property from the object.
$scope.setValue=function(val){
if($scope.obj.selected=="null")
$scope.obj ={"selected":null};
}
<select ng-change="setValue()" ng-model="obj.selected">
<option value=null ng-click="obj.selected=null">Unknown</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
this is a bad idea, you should always have values in your model instead of playing around with null and undefined
This is much easier on Angular2/Angular where you can just use
<option [value]="null">Unknown</option>
This value is no longer a string, but a real null value.

Categories

Resources