convert json string object to integer in ng-view - angularjs

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??
Demo Plunker

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);
}
Plunkr

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.
Working Source code here

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

Related

how to Create dynamic input form which is able to store the array in mongodb?

This is my mongoose schema
var VoSchema =new Schema({
name:{type: String,
required: true},
price:{type: String},
feeds : [Schema.Types.Mixed]
}, {strict: false});
Dynamic input field
<div ng-repeat="item in inputs">
<div>
<input ng-model="item.description">
</div>
<div>
<input ng-model="item.qty">
</div>
<div>
<input ng-model="item.cost"/>
</div>
<div >
{{item.cost * item.qty}}
</div>
</div>
<a class="btn btn-primary" href ng-click="addfield()" >[+]</a>
</div>
controller for angularjs
$scope.submitx = function(inv){
$scope.inv.feeds = $scope.inputs.item
console.log(inv);
PostBlog.createInvoice(inv).then(function(data){
console.log(data);
});
$scope.inv= {};
}
$scope.inputs = [];
$scope.addfield=function(){
$scope.inputs.push({ qty:0, cost:0, description:"" })
}
I want to push the data in array to mongodb, how can i achieve this?
please explain if possible in detail? how to use dynamic form in mean stack.

Angular-Js unable to push data into array of controller

HTML:-
<div ng-controller="countryController">
{{name}}
<ul>
<li ng-repeat="country in countries">
{{ country.name }}
<ul ng-show="country.states.length > 0">
<li ng-repeat="state in country.states">
{{ state.name }}
</li>
</ul>
<input type="text" ng-model="newState">
<a href ng-click="addStateState(country)">Add </a>
{{newState}}
</li>
</ul>
</div>
When I key in newState model it appears in client side.
Now i try to get that value into controller and try to push in array of states, its unable to add into states array.
JS Controller:-
myApp.factory('countryService', function($http){
var baseUrl = 'services/'
return {
getCountries : function(){
return $http.get(baseUrl + 'getcountries.php');
}
};
});
myApp.controller('countryController', function($scope, countryService){
countryService.getCountries().success(function(data){
$scope.countries = data;
});
$scope.addStateState = function(country){
country.states.push({'name' : $scope.newState});
$scope.newState = "";
};
});
Your main issue is that your $scope.newState is not available inside $scope.newStateState function. It is bad practice to manipulate an object like $scope within a $scope function. In fact, you are creating multiple multiple objects that are not the same as the $scope that you inject; otherwise, the input boxes for two different countries should match.
Working Plunkr below.
http://plnkr.co/edit/HG3zWG?p=preview
JS:
angular.module('myApp',[])
.controller('countryController', function($scope){
$scope.countries = [
{ name: 'USA', states:[
{name: 'Virginia'},
{name: 'Utah'}
]
},
{ name: 'Brazil', states:[
{name: 'Pernabuco'}
]
}
];
$scope.addStateState = function(country, data){
country.states.push({'name' : data.newState});
data.newState = "";
};
});
HTML:
<div ng-controller="countryController">
{{name}}
<ul>
<li ng-repeat="country in countries">
{{ country.name }}
<ul ng-show="country.states.length > 0">
<li ng-repeat="state in country.states">
{{ state.name }}
</li>
</ul>
<input type="text" ng-model="data.newState" />
Add
{{data.newState}}
</li>
</ul>
</div>
When you are dealing with things like ng-repeat, ng-if, or ng-include, they each create a new scope. This means that when you try to bind to a primitive on the root level of that scope, it will get dereferences when you update the value. So, you need to put your primitives inside of an object. John Papa's style guide recommends making a "vm" property on your scope. vm stands for view model.
Here is a jsfiddle of how to use it.
http://jsfiddle.net/fbLycnpg/
vm.newState

angularjs model reload after item delete

I'm pretty new in angularjs and I have no idea how do this.
<div class="userData" ng-repeat="user in users">
<div class="float"
<img ng-click="deleteUser($event)" src="myurl">
</div>
<div class="userDiv"
<input type="checkbox" ng-model="user.active" ng-click="handleUserActive()">
<input type="text" ng-model="user.text">
</div>
</div>
I need remove a item when the user click the img.
My model is:
$scope.users = [
{active: true, text: text}
]
Just do:
<img ng-click="deleteUser($index)" src="myurl">
And the method:
$scope.deleteUser = function(index) {
$scope.users.splice(index, 1)
}
What tymeJV said, however, you want to pass the object as the parameter rather than the index like this:
<img ng-click="deleteUser(user)" src="myurl">
$scope.deleteUser = function(user) {
var index = $scope.users.indexOf(user);
$scope.users.splice(index, 1)
}
The reason why is the index can change if you do an orderBy on the ng-repeat.
See an example here: http://jsfiddle.net/6a5zT/

parseInt not converting multiple string to int

it was a very simple but don't no why i can't solve it.
I am trying to convert string to integer from json, it converts 1st object but from second object it doesn't:
HTML:
<body ng-controller="myApp">
<ul ng-repeat="vals in json_arr" ng-init="parseId(vals)">
<li>
<input type="number" ng-model="vals.id" />
</li>
<li>
<input type="number" ng-model="vals.id1" />
</li>
<li>
<input type="number" ng-model="vals.id2" />
</li>
</ul>
</body>
Controller:
app.controller('myApp', function($scope) {
$scope.json_arr = [{
'id': '1',
'id1': '2',
'id2': '3'
}];
$scope.parseId = function(val) {
val.id = parseInt(val.id);
}
});
DEMO PLUNKER
Aahhhhh that's my mistake, In parseId function i only parse val.id.
The correct 1 is:
$scope.parseId = function(val) {
val.id = parseInt(val.id);
val.id1 = parseInt(val.id1);
val.id2 = parseInt(val.id2);
}
change your code with this one
$scope.parseId = function(val) {
val.id = parseInt(val.id);
val.id1 = parseInt(val.id1);
val.id2 = parseInt(val.id2);
}
or you can change your json_arr variable than you don't need to change string to int
$scope.json_arr = [{
'id': 1,
'id1': 2,
'id2': 3
}];
Directives are executed in order from highest priority to lowest priority when defined on the same element. ng-repeat has a directive priority level of 1000, but ng-init has a directive priority of 450. ng-repeat also has a terminal property - meaning it is the last directive to execute, and no other directives can execute after it. There-in lies the problem. The ng-repeat executes first, and because it is terminal, it will not allow ng-init to execute after.
To solve this, move the ng-init to the first li below:
<body ng-controller="myApp">
<ul ng-repeat="vals in json_arr">
<li ng-init="parseId(vals)">
<input type="number" ng-model="vals.id" />
</li>
<li>
<input type="number" ng-model="vals.id1" />
</li>
<li>
<input type="number" ng-model="vals.id2" />
</li>
</ul>
</body>
This works because ng-model has a priority of 0, so it will execute after ng-init.
[EDIT]
I realized there is a logic error in the code you posted. The other two answers have already addressed it, but I'll post it again here for completeness:
$scope.parseId = function(val) {
val.id = parseInt(val.id);
val.id1 = parseInt(val.id1);
val.id2 = parseInt(val.id2);
}

Select a value from typeahead shows Objec object

I am working on Single Page Application and using Angular-TypeAhead when i write something in textbox it shows me suggestions but when i select the suggestion then the values of Textbox become Object object instead of name
here is my HTML Markup
<div class="bs-example" style="padding-bottom: 24px;" append-source>
<form class="form-inline" role="form">
<div class="form-group">
<label><i class="fa fa-globe"></i> State</label>
<input type="text" class="form-control" ng-model="selectedState" ng-options="state.FirstName for state in states" placeholder="Enter state" bs-typeahead>
</div>
</form>
</div>
and here is my AngularJS code
var app = angular.module('mgcrea.ngStrapDocs', ['ngAnimate', 'ngSanitize', 'mgcrea.ngStrap'])
.controller('TypeaheadDemoCtrl', function ($scope, $templateCache, $http) {
$scope.selectedState = '';
$http.get('/api/servicesapi/GetAllClients')
.then(
function (result) {
//success
$scope.states = result.data;
},
function () {
//error
});
});
see the images here
Change ng-options="state.FirstName for state in states" to ng-options="state as state.FirstName for state in states"
This is the solution in Angular 4 and not angularJS
I added [inputFormatter]="formatMatches" to format the input (ngmodel) and [resultFormatter]="formatMatches" to format the data displayed
<input id="typeahead-format" type="text" [(ngModel)]="clickedItem"
name="profile" (selectItem)="selectedItem($event)"
[resultFormatter]="formatter" [inputFormatter]="formatter"
[ngbTypeahead]="search" #instance="ngbTypeahead"/>
and the formatter function is like this:
formatter = (x: { label: string }) => x.label;
x: is the object
For anyone using angular bootstrap and finding the same issue, I spent too long on this.
Essentially you need to consider the model to be a string on the way out and then converted to a string from the complex model returned from the api call.
You then need to hook into the OnSelect method to extract the complex object and store this (or the unique id form the object) in a separate variable. It is right then in the documents, but it is not given much prominence given that you would normally want a key / value pair from a typeahead. Not just a string.
https://valor-software.com/ngx-bootstrap/#/typeahead#on-select
Here is a code snippet from a typeahead which works fine, to set the search as the [name] value from a complex object and the selectedObject to be the whole item.
<pre class="card card-block card-header">Search: {{ search | json }}</pre>
<pre class="card card-block card-header">Selected: {{ selectedOption | json }}</pre>
<ng-template #customItemTemplate let-model="item" let-index="index">
<div>
<p>This is: {{ model.name }} Number: {{ model.id }} Index: {{ index }}</p>
<p>Some secondary information about {{ model.name }}</p>
</div>
</ng-template>
<input [(ngModel)]="search"
[typeahead]="suggestions$"
typeaheadOptionField="name"
(typeaheadOnSelect)="onSelect($event)"
[typeaheadAsync]="true"
typeaheadWaitMs="500"
[typeaheadMinLength]="3"
[typeaheadItemTemplate]="customItemTemplate"
class="form-control"
placeholder="Enter a street name">
<div class="alert alert-danger" role="alert" *ngIf="errorMessage">
{{ errorMessage }}
</div>
then in my component I have
ngOnInit(): void {
this.suggestions$ = new Observable((observer: Observer<string>) => {
observer.next(this.search);
}).pipe(
switchMap((query: string) => {
if (query) {
return this.YOURSERVICE.YOURMETHOD(query);
}
return of([]);
})
);
}
onSelect(event: TypeaheadMatch): void {
this.selectedOption = event.item;
}
your method should return an interface with a [name] property
This should be enough to get going. This is very old, but I passed through here before finding what I needed.

Resources