How to create dictionary like model binding in AngularJS - javascript

On my page I have dynamically generated input tags from database. Those fields could look like that:
<input id='customField-Street' type='text' />
<input id='customField-Height' type='text' />
<input id='customField-IsBlack' type="checkbox" />
<select id='customField-Car'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>
I need to find a way to set a model binding in following key-value format:
$scope.customFieldsDictionary = [{
"Key": "customField-Street",
"Value": "SomeStreet"
}, {
"Key": "customField-Height",
"Value": "125"
}, {
"Key": "customField-IsBlack",
"Value": "true"
}, {
"Key": "customField-Car",
"Value": "volvo"
}];
I need to have key-value format since my service accept custom data in that format.
Question:
How to set AngularJS two way binding between input fields and $scope.customFieldsDictionary field in specified dictionary like format.

<div ng-repeat="obj in customFieldsDictionary">
<input ng-model="obj.Value" id='{{obj.Key}}' ng-if="obj.Key ==
'customField-Street' || obj.Key == 'customField-Height'" type='text'/>
<input ng-model="obj.Value" id='{{obj.Key}}' ng-if="obj.Key ==
'customField-IsBlack'" type="checkbox" />
<select ng-model="obj.Value" id='{{obj.Key}}' ng-if="obj.Key ==
'customField-Car'" ng-options="car for car in cars"></select>
</div>
Controller:
function ctrl($scope){
$scope.cars = ["Volvo","Saab"];
$scope.customFieldsDictionary = [{
...
}];
}

Related

How to trigger selection of an option using Jquery [duplicate]

I am using Angular JS and I need to set a selected option of a dropdown list control using angular JS. Forgive me if this is ridiculous but I am new with Angular JS
Here is the dropdown list control of my html
<select ng-required="item.id==8 && item.quantity > 0" name="posterVariants"
ng-show="item.id==8" ng-model="item.selectedVariant"
ng-change="calculateServicesSubTotal(item)"
ng-options="v.name for v in variants | filter:{type:2}">
</select>
After it gets populated I get
<select ng-options="v.name for v in variants | filter:{type:2}" ng-change="calculateServicesSubTotal(item)"
ng-model="item.selectedVariant" ng-show="item.id==8" name="posterVariants"
ng-required="item.id==8 && item.quantity > 0" class="ng-pristine ng-valid ng-valid-required">
<option value="?" selected="selected"></option>
<option value="0">set of 6 traits</option>
<option value="1">5 complete sets</option>
</select>
How can I set the control for value="0" to be selected?
I hope I understand your question, but the ng-model directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant. This means that changing item.selectedVariant in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant has a value of 0, that item should get selected.
If variants is an array of objects, item.selectedVariant must be set to one of those objects. I do not know which information you have in your scope, but here's an example:
JS:
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
HTML:
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
This would leave the "b" item to be selected.
I don't know if this will help anyone or not but as I was facing the same issue I thought of sharing how I got the solution.
You can use track by attribute in your ng-options.
Assume that you have:
variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]
You can mention your ng-options as:
ng-options="v.name for v in variants track by v.id"
Hope this helps someone in future.
If you assign value 0 to item.selectedVariant it should be selected automatically.
Check out sample on http://docs.angularjs.org/api/ng.directive:select which selects red color by default by simply assigning $scope.color='red'.
i see here already wrote good answers, but sometime to write the same in other form can be helpful
<div ng-app ng-controller="MyCtrl">
<select ng-model="referral.organization" ng-options="c for c in organizations"></select>
</div>
<script type='text/javascript'>
function MyCtrl($scope) {
$scope.organizations = ['a', 'b', 'c', 'd', 'e'];
$scope.referral = {
organization: $scope.organizations[2]
};
}
</script>
Simple way
If you have a Users as response or a Array/JSON you defined, First You need to set the selected value in controller, then you put the same model name in html. This example i wrote to explain in easiest way.
Simple example
Inside Controller:
$scope.Users = ["Suresh","Mahesh","Ramesh"];
$scope.selectedUser = $scope.Users[0];
Your HTML
<select data-ng-options="usr for usr in Users" data-ng-model="selectedUser">
</select>
complex example
Inside Controller:
$scope.JSON = {
"ResponseObject":
[{
"Name": "Suresh",
"userID": 1
},
{
"Name": "Mahesh",
"userID": 2
}]
};
$scope.selectedUser = $scope.JSON.ResponseObject[0];
Your HTML
<select data-ng-options="usr.Name for usr in JSON.ResponseObject" data-ng-model="selectedUser"></select>
<h3>You selected: {{selectedUser.Name}}</h3>
It can be usefull. Bindings dose not always work.
<select id="product" class="form-control" name="product" required
ng-model="issue.productId"
ng-change="getProductVersions()"
ng-options="p.id as p.shortName for p in products">
</select>
For example. You fill options list source model from rest-service. Selected value was known befor filling list and was set. After executing rest-request with $http list option be done. But selected option is not set. By unknown reasons AngularJS in shadow $digest executing not bind selected as it shuold be. I gotta use JQuery to set selected. It`s important! Angular in shadow add prefix to value of attr "value" for generated by ng-repeat optinos. For int it is "number:".
$scope.issue.productId = productId;
function activate() {
$http.get('/product/list')
.then(function (response) {
$scope.products = response.data;
if (productId) {
console.log("" + $("#product option").length);//for clarity
$timeout(function () {
console.log("" + $("#product option").length);//for clarity
$('#product').val('number:'+productId);
//$scope.issue.productId = productId;//not work at all
}, 200);
}
});
}
Try the following:
JS file
this.options = {
languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);
HTML file
<div class="form-group col-sm-6">
<label>Preferred language</label>
<select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
</select>
</div>
This is the code what I used for the set selected value
countryList: any = [{ "value": "AF", "group": "A", "text": "Afghanistan"}, { "value": "AL", "group": "A", "text": "Albania"}, { "value": "DZ", "group": "A", "text": "Algeria"}, { "value": "AD", "group": "A", "text": "Andorra"}, { "value": "AO", "group": "A", "text": "Angola"}, { "value": "AR", "group": "A", "text": "Argentina"}, { "value": "AM", "group": "A", "text": "Armenia"}, { "value": "AW", "group": "A", "text": "Aruba"}, { "value": "AU", "group": "A", "text": "Australia"}, { "value": "AT", "group": "A", "text": "Austria"}, { "value": "AZ", "group": "A", "text": "Azerbaijan"}];
for (var j = 0; j < countryList.length; j++) {
//debugger
if (countryList[j].text == "Australia") {
console.log(countryList[j].text);
countryList[j].isSelected = 'selected';
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<label>Country</label>
<select class="custom-select col-12" id="Country" name="Country" >
<option value="0" selected>Choose...</option>
<option *ngFor="let country of countryList" value="{{country.text}}" selected="{{country.isSelected}}" > {{country.text}}</option>
</select>
try this on an angular framework
JS:
$scope.options = [
{
name: "a",
id: 1
},
{
name: "b",
id: 2
}
];
$scope.selectedOption = $scope.options[1];

angularjs dynamic sort of JSON data

I want to show below data in ascending order in select box.
Data is as under :-
[
{
"value": "MKZ_2017_LCN2014",
"text": "林肯MKZ"
},
{
"value": "MKX_2016_LCN2014",
"text": "林肯MKX"
},
{
"value": "MKC_presidential_LCN2014",
"text": "林肯总统系列MKC(Oasis)"
},
{
"value": "MKZ_2015_360used_LCN2014",
"text": "林肯MKZ(360)"
}
]
View code is :-
<select
class="select-modal"
ng-model="key3"
id="model-03-1"
name="third-primary-model"
ng-options="nameplate.text for nameplate in thirdLevelDropDown track by nameplate.value"
ng-change="getCarModel3(key3)"
>
<option value="">Select</option>
</select>
I want to sort select box on the name of text.
Appreciate your help
You can do this, Use | orderBy:'text'
<select class="select-modal" ng-model="key3" id="model-03-1" name="third-primary-model" ng-options="nameplate.text for nameplate in thirdLevelDropDown | orderBy:'text'" ng-change="getCarModel3(key3)">
<option value="">Select</option>
</select>
DEMO
This works for me.
ng-options="nameplate.text for nameplate in (models | orderBy: 'text') track by nameplate.value"

angularjs: ng-model double object

I try to achieve a double nested object. (Example Below)
The Problem is that my current Code is generating a Array inside a Object.
<div ng-if="newResultUnits()" ng-repeat="set in sets" ng-model="newexercise.sets[$index]">
<label>Set {{$index+1}}</label>
<label>
<label>
<input type="text" ng-repeat="resultUnit in newResultUnits()" ng-model="newexercise.sets[$parent.$index][$index].value" placeholder="{{resultUnit.name}}">
</label>
</label>
</div>
Example (the name attr is added later):
{
name:"MultiTest",
sets:[
{
0:{
value:"10",
name:"Kg"
},
1:{
value:"10",
name:"Wdh"
}
}
]
}
This is how it should be: (Please note the doubble [[ and the missing 0:)
{
"name": "MultiTest",
"sets": [
[
{
"value": "10",
"name": "Kg"
},
{
"value": "10",
"name": "Wdh"
}
]
]
}
Im sorry if I mixedup Array and Object.. Thanks!
You need properly initialize your data structures. So in controller begin with
$scope.newexercise = { sets: [] };
So Angular knows that you want $scope.newexercise to be an array. Then in template use ngInit on every inner loop ng-init="newexercise.sets[$parent.$index] = []":
<div ng-repeat="set in sets">
<label>Set {{$index+1}}</label>
<label>
<label>
<input type="text"
ng-repeat="resultUnit in newResultUnits()"
ng-init="newexercise.sets[$parent.$index] = []"
ng-model="newexercise.sets[$parent.$index][$index].value"
placeholder="{{resultUnit.name}}">
</label>
</label>
</div>
Demo: http://plnkr.co/edit/s1rInT8rLg50ISsSVxyV?p=preview

"selected" attribute on select option being ignored [duplicate]

I am using Angular JS and I need to set a selected option of a dropdown list control using angular JS. Forgive me if this is ridiculous but I am new with Angular JS
Here is the dropdown list control of my html
<select ng-required="item.id==8 && item.quantity > 0" name="posterVariants"
ng-show="item.id==8" ng-model="item.selectedVariant"
ng-change="calculateServicesSubTotal(item)"
ng-options="v.name for v in variants | filter:{type:2}">
</select>
After it gets populated I get
<select ng-options="v.name for v in variants | filter:{type:2}" ng-change="calculateServicesSubTotal(item)"
ng-model="item.selectedVariant" ng-show="item.id==8" name="posterVariants"
ng-required="item.id==8 && item.quantity > 0" class="ng-pristine ng-valid ng-valid-required">
<option value="?" selected="selected"></option>
<option value="0">set of 6 traits</option>
<option value="1">5 complete sets</option>
</select>
How can I set the control for value="0" to be selected?
I hope I understand your question, but the ng-model directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant. This means that changing item.selectedVariant in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant has a value of 0, that item should get selected.
If variants is an array of objects, item.selectedVariant must be set to one of those objects. I do not know which information you have in your scope, but here's an example:
JS:
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
HTML:
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
This would leave the "b" item to be selected.
I don't know if this will help anyone or not but as I was facing the same issue I thought of sharing how I got the solution.
You can use track by attribute in your ng-options.
Assume that you have:
variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]
You can mention your ng-options as:
ng-options="v.name for v in variants track by v.id"
Hope this helps someone in future.
If you assign value 0 to item.selectedVariant it should be selected automatically.
Check out sample on http://docs.angularjs.org/api/ng.directive:select which selects red color by default by simply assigning $scope.color='red'.
i see here already wrote good answers, but sometime to write the same in other form can be helpful
<div ng-app ng-controller="MyCtrl">
<select ng-model="referral.organization" ng-options="c for c in organizations"></select>
</div>
<script type='text/javascript'>
function MyCtrl($scope) {
$scope.organizations = ['a', 'b', 'c', 'd', 'e'];
$scope.referral = {
organization: $scope.organizations[2]
};
}
</script>
Simple way
If you have a Users as response or a Array/JSON you defined, First You need to set the selected value in controller, then you put the same model name in html. This example i wrote to explain in easiest way.
Simple example
Inside Controller:
$scope.Users = ["Suresh","Mahesh","Ramesh"];
$scope.selectedUser = $scope.Users[0];
Your HTML
<select data-ng-options="usr for usr in Users" data-ng-model="selectedUser">
</select>
complex example
Inside Controller:
$scope.JSON = {
"ResponseObject":
[{
"Name": "Suresh",
"userID": 1
},
{
"Name": "Mahesh",
"userID": 2
}]
};
$scope.selectedUser = $scope.JSON.ResponseObject[0];
Your HTML
<select data-ng-options="usr.Name for usr in JSON.ResponseObject" data-ng-model="selectedUser"></select>
<h3>You selected: {{selectedUser.Name}}</h3>
It can be usefull. Bindings dose not always work.
<select id="product" class="form-control" name="product" required
ng-model="issue.productId"
ng-change="getProductVersions()"
ng-options="p.id as p.shortName for p in products">
</select>
For example. You fill options list source model from rest-service. Selected value was known befor filling list and was set. After executing rest-request with $http list option be done. But selected option is not set. By unknown reasons AngularJS in shadow $digest executing not bind selected as it shuold be. I gotta use JQuery to set selected. It`s important! Angular in shadow add prefix to value of attr "value" for generated by ng-repeat optinos. For int it is "number:".
$scope.issue.productId = productId;
function activate() {
$http.get('/product/list')
.then(function (response) {
$scope.products = response.data;
if (productId) {
console.log("" + $("#product option").length);//for clarity
$timeout(function () {
console.log("" + $("#product option").length);//for clarity
$('#product').val('number:'+productId);
//$scope.issue.productId = productId;//not work at all
}, 200);
}
});
}
Try the following:
JS file
this.options = {
languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);
HTML file
<div class="form-group col-sm-6">
<label>Preferred language</label>
<select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
</select>
</div>
This is the code what I used for the set selected value
countryList: any = [{ "value": "AF", "group": "A", "text": "Afghanistan"}, { "value": "AL", "group": "A", "text": "Albania"}, { "value": "DZ", "group": "A", "text": "Algeria"}, { "value": "AD", "group": "A", "text": "Andorra"}, { "value": "AO", "group": "A", "text": "Angola"}, { "value": "AR", "group": "A", "text": "Argentina"}, { "value": "AM", "group": "A", "text": "Armenia"}, { "value": "AW", "group": "A", "text": "Aruba"}, { "value": "AU", "group": "A", "text": "Australia"}, { "value": "AT", "group": "A", "text": "Austria"}, { "value": "AZ", "group": "A", "text": "Azerbaijan"}];
for (var j = 0; j < countryList.length; j++) {
//debugger
if (countryList[j].text == "Australia") {
console.log(countryList[j].text);
countryList[j].isSelected = 'selected';
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<label>Country</label>
<select class="custom-select col-12" id="Country" name="Country" >
<option value="0" selected>Choose...</option>
<option *ngFor="let country of countryList" value="{{country.text}}" selected="{{country.isSelected}}" > {{country.text}}</option>
</select>
try this on an angular framework
JS:
$scope.options = [
{
name: "a",
id: 1
},
{
name: "b",
id: 2
}
];
$scope.selectedOption = $scope.options[1];

Fill select with object datasource

Controller:
$scope.obj = {
"category": {
"value": "1",
"synonym": ""
},
"name": {
"value": "2",
"synonym": ""
}
};
I have html like this:
<select
ng-model="model",
ng-options="value.value as key for (key , value) in obj",
bs-select>
</select>
I want to get this result:
<option value="1"> category </option>
<option value="2"> name </option>
But i get this:
<option value="category"> category </option>
<option value="name"> name </option>
Can you help me to find a problem?
What you are doing is correct. The drop down list is a bit confusing since you should get the value by accessing from the model rather than from DOM. So whatever rendered in HTML doesn't matter.
Here is one example (FIDDLE), when you change the drop down, the actual value will be passed in. Though it looks a bit different in the rendered HTML, this is the nature of Angularjs being a self-contained scope for 2-way data binding.
function ctrl($scope) {
$scope.obj = {
"category": {
"value": "1",
"synonym": ""
},
"name": {
"value": "2",
"synonym": ""
}
};
$scope.model = "1";
$scope.$watch('model', function(newValue, oldValue){
console.log(newValue);
});
}

Categories