'convert json string object to integer in ng-view
i am trying to convert json object to integer in ng-view:
json string:
$scope.json_arr = [{
'id': '1',
'name': 'abc'
},
{
'id': '2',
'name': 'xyz'
}];
in view:
<ul ng-repeat="vals in json_arr">
<li><input type="number" ng-model="vals.id" /></li>
<li><input type="text" ng-model="vals.name" /></li>
</ul>
when i see the ouput, the number field is coming blank as the value of the id object is string.
How do i convert string 'id':'1' to integer??
Solution 1:[1]
Use ng-init, this will run whenever a new element in the array appears for ng-repeat, if you use it like this:
<ul ng-repeat="vals in json_arr" ng-init="parseId(vals)">
<li><input type="number" ng-model="vals.id" /></li>
<li><input type="text" ng-model="vals.name" /></li>
</ul>
Then all that's left is to write the parseId function referenced
$scope.parseId = function(val){
val.id = parseInt(val.id);
}
Solution 2:[2]
try it
Html side
<ul ng-repeat="vals in json_arr">
<li> <input type="number" value="{{convertToInt(vals.id)}}"/></li>
<li><input type="text" ng-model="vals.name" /> </li>
</ul>
Js Side
$scope.convertToInt= function (value) {
return parseInt(value);
};
It's working for me.
Solution 3:[3]
if you are using angular form to store one or more variable values and pass a request for api post or put method, example:
component.ts file
`loginForm: FormGroup;
mockService: ServiceName;
this.loginForm = this.formBuilder.group({
Id: [''],
empID: [''],
roomID: ['']
});
this.loginForm.get('Id').setValue(parseInt(this.Id));
this.loginForm.get('empID').setValue(parseInt(this.empID));
this.loginForm.get('roomID').setValue(parseInt(this.roomID));
let request = JSON.stringify(this.loginForm.value);
this.mockloginService.loginValuesCheckmethod(request).subscribe((response) => {
if (response.isSuccess && response.responseCode === '200') {}
This will pass payload value as int
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Philipp Gayret |
| Solution 2 | |
| Solution 3 | Niranjana V S |
