Select value not selected in Angularjs - angularjs

I have this html markup:
<div ng-repeat="prop in props" style="margin-bottom: 10px;">
<label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.AddressLine1}})</label><div class="col-md-8">
<select ng-model="prop.Grade" class="form-control" ng-options="opt.name for opt in propGradings track by opt.id"> <option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}</option> </select>
</div>
</div>
This static array to fill in the dropdown:
$scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];
I'm able to load the items in the dropdown, but I'm not able to preselect the correct value based on the prop.Grade value.
HTML Output:
Any idea what am I doing wrong?

When selecting options from a dropdown, type matters for binding purposes. When using ng-options, you can use as to bind something to the model as a non-string value. In your case, you may want to bind to the integer value of the id.
Syntax: select as label for value in array
> select: The value that gets bound to ng-model
> label: What value visibly shows up in the dropdown
> value: Current item in array
> array: Data source for generating the options
Example of binding to an integer value:
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.props = [{Grade: 1}];
$scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Binding with an integer value:
<div ng-repeat="prop in props" style="margin-bottom: 10px;">
<label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.AddressLine1}})</label>
<div class="col-md-8">
<select ng-model="prop.Grade" class="form-control" ng-options="opt.id as opt.name for opt in propGradings">
<option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}</option>
</select>
</div>
</div>
</div>
Example of binding to a string value:
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.props = [{Grade: "1"}];
$scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Binding with a string value:
<div ng-repeat="prop in props" style="margin-bottom: 10px;">
<label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.AddressLine1}})</label>
<div class="col-md-8">
<select ng-model="prop.Grade" class="form-control" ng-options="opt.name as opt.name for opt in propGradings">
<option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}</option>
</select>
</div>
</div>
</div>

Related

Multiple check box not working when it's value same vuejs

When I check Apple it's all check Pineapple. When I unchecked Pineapple it's also unchecked Apple.
both Tag id different. How can I check only one Apple instead of Pineapple?
var demo = new Vue({
el: '#demo',
data: {
checkedNames: []
},
computed: {
computedNames() {
let names = this.checkedNames;
return names.toString();
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="demo">
<input type="checkbox" id="50" value="50" v-model="checkedNames">
<label for="Apple">Apple</label>
<input type="checkbox" id="51" value="51" v-model="checkedNames">
<label for="Banana">Banana</label>
<input type="checkbox" id="52" value="50" v-model="checkedNames">
<label for="Pineapple">Pineapple</label>
<br>
<span>Checked names: {{ checkedNames }}</span>
<span>Computed names (reversed order): {{ computedNames }}</span>
</div>
Vue is data-driven. Since both your Apple and Pineapple checkboxes have the same value, Vue considers them to be the same.
It sounds like you want to use separate objects entirely so try this
var demo = new Vue({
el: '#demo',
data: () => ({
options: [{
id: 50,
label: "Apple",
price: 50
}, {
id: 51,
label: "Banana",
price: 51
}, {
id: 52,
label: "Pineapple",
price: 50
}],
selections: []
}),
computed: {
computedNames: ({ selections }) =>
selections.map(({ label }) => label).join(", ")
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="demo">
<template v-for="fruit in options">
<input
:key="fruit.id"
type="checkbox"
:value="fruit"
v-model="selections"
:id="`fruit_${fruit.id}`"
>
<label :for="`fruit_${fruit.id}`">{{ fruit.label }}</label>
</template>
<br>
<span>Computed names: {{ computedNames }}</span>
<pre>Selections: {{ selections }}</pre>
</div>

Can't add src img to $scope.data

I want to be able to select a person, and when selected, I see his values(name, tel, email, ..):
html :
<td class="leftAlign">
<span class="nullable">
<select ng-model="data.selectedPerson" ng-options="x.name for x in persons">
<option value="">-- Person --</option></select>
<br><br>
{{data.selectedPerson.name}}<br>
{{data.selectedPerson.Addrstr1}}<br>
{{data.selectedPerson.Tel}}<br>
{{data.selectedPerson.Mail}}<br>
<img data-ng-src="{{data.selectedPerson.img}}">
</span>
</td>
It works fine, I can see all the values of the person, and the img too. To reset everything in my html form I have a reset button, with the JS:
$scope.reset = function() {
$scope.data = {};
};
however, I can't erase the img.
in the JS, the persons values are in the array :
$scope.person = [
{name : "MrPerson1",
Addrstr1:"59 road",
Tel: "0234225163",
Email : "direction#gmail.com ",
img : "images/person1.PNG",
}];
Could you help me please?
Check this example, you are removing the data but not the ng-model of the <select>
var Controller = function() {
var vm = this
vm.persons = [{
name: "MrPerson1",
Addrstr1: "59 road",
Tel: "0234225163",
Email: "direction#gmail.com ",
img: "https://lh3.googleusercontent.com/-crlUFIoyB3k/UdzsGwV__AI/AAAAAAAAAXs/ErA8XESRgwk/5LsFP.gif",
}, {
name: "MrPerson2",
Addrstr1: "59 road",
Tel: "0234225163",
Email: "direction#gmail.com ",
img: "https://lh3.googleusercontent.com/-Ta_b7Z96-mE/Ud2hTqB-84I/AAAAAAAABEQ/BPY_MIbLitc/SausageDogAnimation.gif",
}, {
name: "MrPerson3",
Addrstr1: "59 road",
Tel: "0234225163",
Email: "direction#gmail.com ",
img: "https://www.gravatar.com/avatar/e27096ea0e246d04139047d40ff566d2?s=32&d=identicon&r=PG",
}];
vm.data = vm.persons
vm.reset = function() {
vm.data.selectedPerson = {}
};
};
angular
.module('app', [])
.controller('Controller', Controller);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Controller as vm">
<button ng-click="vm.reset()">Reset</button>
<select ng-model="vm.data.selectedPerson" ng-options="x.name for x in vm.data">
<option value="">-- Person --</option>
</select>
<br><br> {{vm.data.selectedPerson.name}}
<br> {{vm.data.selectedPerson.Addrstr1}}
<br> {{vm.data.selectedPerson.Tel}}
<br> {{vm.data.selectedPerson.Mail}}
<br>
<img ng-if="vm.data.selectedPerson.img" ng-src="{{vm.data.selectedPerson.img}}" />
</div>

Angularjs : Filter conditionaly

<div class="district-list" ng-repeat="office in offices | filter : {'DisplayOffice' : officeLocationLevelList.searchText}|limitTo:1">
Have a multilevel list of data. depending on the condition i want to filter the data.(First Level/ inner level). If the first level is selected then i have to search with one json attribute and if the inner level is selected then search with another json attribute. I have set it in a scope variable. How can use scope variable instead of 'DisplayOffice'
you can bind a function to filter which returns the filter condition using scope variables.
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.data = [
{
id: 1,
name: 'name1'
},{
id: 2,
name: 'name2'
},{
id: 3,
name: 'name3'
},{
id: 3,
name: 'aaaaa'
}
];
$scope.getCondition = function() {
var obj = {};
obj[$scope.key] = $scope.value;
return obj;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
Key: <input type="text" ng-model="key">
Value: <input type="text" ng-model="value">
<div ng-repeat="item in data | filter: {[key]:value}">
{{item.name}}
</div>
</div>
and there is another way while using ES6' new feature {[key]: value}, but this may now work for some browsers.
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.$watch("key", function() {
console.log({[$scope.key]:$scope.value});
});
$scope.$watch("value", function() {
console.log({[$scope.key]:$scope.value});
});
$scope.data = [
{
id: 1,
name: 'name1'
},{
id: 2,
name: 'name2'
},{
id: 3,
name: 'name3'
},{
id: 3,
name: 'aaaaa'
}
];
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
Key: <input type="text" ng-model="key">
Value: <input type="text" ng-model="value">
<div ng-repeat="item in data | filter: {[key]: value}">
{{item.name}}
</div>
</div>

Adding the input fields dynamically from nested json object in angulajs

var inputs={
'firstname': '',
'lastName':'',
'account':{
'role':'',
'status':''
}
}
This is my model array. I want to display it dynamically in Webpage and by modifying the json array the changes should affect the form too.
Here is the image
UPD:
for your situation, you can use ng-switch to generate elements according to conditions.
Notice(already included in the code snippet):
ng-repeat will generate it's own scope, so your model won't update unless you bind it with the original scope. ref here.
OLD ANSWER:
use ng-model to implement two-way-databinding.
refer the code snippet below:
angular.module("app", []).controller("myCtrl", function($scope) {
$scope.inputs = {
'firstname': 'test first name',
'lastName': 'test last name',
'account': {
'role': 'test role',
'status': 'test status'
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<!-- First Name: <input type="text" ng-model="inputs.firstname"><br>
Last Name: <input type="text" ng-model="inputs.lastName"><br> Account Role: <input type="text" ng-model="inputs.account.role"><br>
Account Status: <input type="text" ng-model="inputs.account.status"><br> -->
<div ng-repeat="(key1, value) in inputs" ng-switch="key1">
<div ng-switch-when="account">
<div ng-repeat="(key2, value2) in value">
{{key1 | uppercase}} => {{ key2 | uppercase}}
<input type="text" ng-model="inputs[key1][key2]">
</div>
</div>
<div ng-switch-default>
{{key1 | uppercase}}
<input type="text" ng-model="inputs[key1]">
</div>
</div>
{{inputs}}
</div>
/My html should look like this/
<head>
<script data-require="angular.js#1.4.1" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<script type="text/ng-template" id="tree-structure">
<label>{{dt}}</label><input type="text" name="" value="{{dt.label}}">
<ul class="childElement">
<li ng-repeat="dt in dt.nodes" ng-include="'tree-structure'">
</li>
</ul>
</script>
<ul class="parentList">
<li ng-repeat="(key, value) in inputs" >
<div ng-repeat="(key1, value1) in value">
<label>{{key1}}</label>
<input type="text" name="" value="{{value1}}">
<!-- <div ng-repeat="(key2, value2) in value1">
<label>{{key2}}</label><input type="text" name="" value="{{value2}}">
</div> -->
</div>
<div ></div>
</li>
</div>
</ul>
</body>
</html>
Some observations :
Your JSON should be formatted properly with type of the field.
If you want to access the object properties as a form fields then it should be structured in a good way so that we can dynamically add the type of the field as well.
[{
name: 'firstName',
type: 'text'
}, {
name: 'lastname',
type: 'text'
}, {
account: [{
name: 'role',
type: 'text'
}, {
name: 'status',
type: 'text'
}]
}]
As your JSON have nested objects. So, first iterate it recursively and create one dimensional array then create the fields using 1D array.
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
var inputs = [{
name: 'firstName',
type: 'text'
}, {
name: 'lastname',
type: 'text'
}, {
account: [{
name: 'role',
type: 'text'
}, {
name: 'status',
type: 'text'
}]
}];
$scope.fields = [];
function structuredObj(obj) {
for (var i in obj) {
if (obj[i].type == 'text') {
$scope.fields.push(obj[i]);
} else {
structuredObj(obj[i])
}
}
};
structuredObj(inputs);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<form name="myForm" novalidate>
<div ng-repeat="item in fields" class="form-group">
<input
name="item.name"
type="{{ item.type }}"
placeholder="{{ item.name }}"
ng-model="item.value"
required />
</div>
<button ng-disabled="myForm.$invalid">Submit</button>
</form>
</div>
<div ng-repeat="(key1, value1) in myPersonObj">
<div ng-repeat="(key, value) in value1">
<label>{{key}}</label>
<input type="text" name="" value="{{value}}">
</div>
</div>
var app = angular.module("test",[]);
app.controller("MainCtrl",function($scope){
$scope.inputs = [
{
"firstname" : "Test"
},{
"lastname" : "Test1"
},{
"Account" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account1" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account2" : [
{"role" : {
'dim3': {
'dim4':{
'dim5':'cccc'
}
}
}
},
{"status" : "Test4"},
]
}
];
$scope.person = [];
$scope.myPersonObj = [];
/*console.log($scope.keys(inputs));*/
$scope.checkIndex1 = function(arg, myPersonObj)
{
if (angular.isArray(arg) || angular.isObject(arg)) {
angular.forEach(arg, function (value, key) {
console.log(value);
if(angular.isObject(value) || angular.isArray(value))
{
$scope.checkIndex1(value, myPersonObj);
}
else
{
console.log("pushing");
myPersonObj.push(arg);
}
});
}
else
{
console.log("pushing1");
myPersonObj.push(arg);
}
}
$scope.checkIndex1($scope.inputs, $scope.myPersonObj);
console.log("myPersonObj :"+ JSON.stringify($scope.myPersonObj));
console.log($scope.inputs);

how to populate select option in angular

I have a dynamically created data. Based on this I am creating a form. But problem is option is not added to to the select. What is wrong in this.
customerB :
{
rows:3,
columns: 2,
name: 'customerB',
fields:
[
{type: "select", name:"teacher_id", label: "Teacher" , endpoint: "/teachers", required: true, check:[ { id : "1982", name : "Mr Bob"}, { id : "18273", name : "Mrs Katrine"} ]}
],
}
HTML
<div class="rows" ng-repeat="field in customerB">
<div class="columns" ng-repeat="newvalue in field">
<div class="controls" ng-switch="newvalue.type">
<div class="form-group">
<label class="control-label">{{newvalue.label}}</label>
<select class="form-control" ng-switch-when="select" ng-model="hiii" ng-required="newvalue.required" ng-options="item.id as item.name for item in newvalue.check">
</select>
</div>
</div>
</div>
</div>
You got an object which got an array, inside the array you got another array which is not correctly manipulating.
Try understanding the following code snippet:
HTML:
<select name="repeatSelect" id="repeatSelect">
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
JS
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
]
OR follow the link: https://docs.angularjs.org/api/ng/directive/select
This assumption might be wrong but I think in here ng-repeat="field in customerB" you are accessing object property directly without the scope variable. So you need to add whatever the scope variable name in front of the property name.
<div class="rows" ng-repeat="field in obj.customerB">
Other than that code you provided work perfectly.
Demo
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.obj = { customerB :
{
rows:3,
columns: 2,
name: 'customerB',
fields:
[
{type: "select", name:"teacher_id", label: "Teacher" , endpoint: "/teachers", required: true, check:[ { id : "1982", name : "Mr Bob"}, { id : "18273", name : "Mrs Katrine"} ]}
],
}}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div class="rows" ng-repeat="field in obj.customerB">
<div class="columns" ng-repeat="newvalue in field">
<div class="controls" ng-switch="newvalue.type">
<div class="form-group"> <label class="control-label">{{newvalue.label}}</label> <select class="form-control" ng-switch-when="select" ng-model="hiii" ng-required="newvalue.required" ng-options="item.id as item.name for item in newvalue.check"></select> </div>
</div>
</div>
</div>
</div>

Resources