Storing as key value in Json Angular js - javascript

This is my script File..
app.controller('userController', function PostController($scope, userFactory) {
$scope.users = [];
$scope.user = { items : [] , attributes : [] };
$scope.editMode = false;
$scope.addItem = function (index) {
$scope.user.items.push({
Name: $scope.newItemName,
Value: $scope.newItemValue
});
};
$scope.deleteItem = function (index) {
$scope.user.items.splice(index, 1);
};
}
This is my HTML file
<div class="modal-body">
<form class="form-horizontal" role="form" name="adduserform">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" data-ng-model="user.Name" class="form-control" id="title" placeholder="Your Name" required title="Enter your name" />
</div>
</div>
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Address</label>
<div class="col-sm-10">
<input type="text" data-ng-model="user.Address" class="form-control" id="title" placeholder="Your Address" required title="Enter your address" />
</div>
</div>
<div class="form-group">
<label for="title" class="col-sm-2 control-label">ContactNo</label>
<div class="col-sm-10">
<input type="text" data-ng-model="user.ContactNo" class="form-control" id="title" placeholder="Your ContactNo" required title="Enter your contactno" />
</div>
</div>
<div class="form-group">
<ul class="nav" class="col-sm-2" >
<label for="title" class="col-sm-2 control-label">Variations</label>
<div class="col-sm-10">
<input type="text" value="ItemName" class="form-control" id="title" ng-model="newItemName" required placeholder="Name of new item...">
<input type="text" value="ItemName" class="form-control" id="title" ng-model="newItemValue" required placeholder="Value of new item...">
</div>
<div class="col-sm-offset-3">
<button ng-click="addItem()" class="btn btn-primary" >Add Me</button>
<table class="table table-hover">
<tr data-ng-repeat="item in user.items">
<td>
<p>{{item.Name}}</p>
</td>
<td>
<p>{{item.Value}}</p>
</td>
<td>
<a ng-click="deleteItem($index)" class="delete-Item">x</a>
</td>
</tr>
</table>
</div>
</ul>
</div>
My doubt is that whenever I click addItem it will be stored as Name : "xxx", Value: "yyy", but i want it to be stored as xxx : yyy. Is there a way to do that. Im new to angular js. Please help me. Thank you

Try using this code in your addItem method:
$scope.addItem = function (index) {
var newItem = {};
newItem[$scope.newItemName] = $scope.newItemValue;
$scope.user.items.push(newItem);
};
In this code you first create an object for new item, and then create the property from newItemName and assign it a value from field newItemValue. Then you push this to an array.
One issue with this approach is that your bindings like <p>{{item.Name}}</p> will not work, because there is no property called Name anymore. I don't know why you want to store the data in the format you described, but in order to make the old bindings work you could also use old properties as well:
$scope.addItem = function (index) {
var newItem = {Name: $scope.newItemName, Value: $scope.newItemValue };
newItem[$scope.newItemName] = $scope.newItemValue;
$scope.user.items.push(newItem);
};

Use a map instead of a list for the items:
$scope.user = { items : {} , attributes : [] };
$scope.user.items[$scope.newItemName] = $scope.newItemValue;

Related

Firebase Realtime database update

Hello guys my firebase real-time database update function is updating all the data with new data, I'm attaching the image of the database before the update
And after the update all the fields of A and B are changed into C, the source code is available below :
Frontend:
<form onsubmit="return false">
<input type="hidden" id="hiddenId">
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Course Code</label>
<input type="text" class="form-control uname-box" id="popupCourseCode" aria-describedby="emailHelp" placeholder="Course Code">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Course Title</label>
<input type="text" class="form-control uname-box" id="popupCourseTitle" aria-describedby="emailHelp" placeholder="Course Title">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Subject</label>
<input type="text" class="form-control uname-box" id="popupSubject" aria-describedby="emailHelp" placeholder="Subject">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Credits</label>
<input type="number" class="form-control uname-box" id="popupCredits" aria-describedby="emailHelp" placeholder="Credits">
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label class="uname">Grades</label>
<input type="text" class="form-control uname-box" id="popupGrades" aria-describedby="emailHelp" placeholder="Grades">
</div>
</div>
</form>
Function:
function update() {
firebase.database().ref('academics').orderByKey().once('value', snap => {
snap.forEach((data) => {
var popupCourseCode = document.getElementById('popupCourseCode');
var popupCourseTitle = document.getElementById('popupCourseTitle');
var popupSubject = document.getElementById('popupSubject');
var popupCredits = document.getElementById('popupCredits');
var popupGrades = document.getElementById('popupGrades');
var updates = {
courseCode: popupCourseCode.value,
courseTitle: popupCourseTitle.value,
subject: popupSubject.value,
credits: popupCredits.value,
grade: popupGrades.value,
}
firebase.database().ref('academics/' + data.key).update(updates)
// alert('updated')
console.log(`Update FunctionKey!!!!!!!!!!!! >>>>>>>>> ${data.key}`)
})
// console.log(`Remove FunctionKey!!!!!!!!!!!! >>>>>>>>> ${data.key}`)
})
}
Please provide me a solution. Thanks in anticipation

AngularJS Cannot get form data

Pulling values from a form in AngularJS doesn't appear to be working - for example my form code is:
<form ng-submit="newCompany()">
<div class="form-group">
<label>Name</label><input type="text" name="company_name" id="company_name" tabindex="2" ng-model="newCompany.company_name" class="form-control">
<label>Primary Contact</label><input type="text" name="primary_contact" id="primary_contact" tabindex="2" ng-model="newCompany.primary_contact" class="form-control">
<label>Address</label><input type="text" name="address" id="address" tabindex="2" ng-model="newCompany.address" class="form-control">
<label>Function</label><input type="text" name="function" id="function" tabindex="2" ng-model="newCompany.function" class="form-control">
<label>Telephone</label><input type="text" name="telephone" id="telephone" tabindex="2" ng-model="newCompany.phone" class="form-control">
<label>Fax</label><input type="text" name="fax" id="fax" tabindex="2" ng-model="newCompany.fax" class="form-control">
<label>URL</label></label><input type="text" name="url" id="url" tabindex="2" ng-model="newCompany.url" class="form-control">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="add-submit" id="add-submit" tabindex="10" class="form-control btn btn-primary" value="Add Company">
<br>
<div class="text-center">
<p ng-show="addCompany"><span class="label label-info">{{ addCompany }}</span></p>
</div>
</div>
</div>
</div>
</form>
But in the controller, doing newCompany.name or $scope.newCompany.name, doesn't work. It returns nothing and says newCompany is undefined.
Controller:
app.controller("CompaniesController", ['$scope', 'Companies', function($scope, Companies) {
$scope.title = 'Companies';
$scope.title_sub = 'Add Company';
$scope.companyData = {
company_name: newCompany.company_name,
primary_contact: newCompany.primary_contact,
address: newCompany.address,
function: newCompany.function,
telephone: newCompany.phone,
fax: newCompany.fax,
url: newCompany.url
};
$scope.addCompany = function() {
var company = new Companies($scope.companyData);
company.$save();
};
$scope.companies = Companies.query();
}]);
Can anybody see what is wrong or how to get it to work?
Yes newCompany is undefined please define it before use will solve your problem
$scope.newCompany = {};
$scope.companyData = {
company_name: newCompany.company_name,
primary_contact: newCompany.primary_contact,
address: newCompany.address,
function: newCompany.function,
telephone: newCompany.phone,
fax: newCompany.fax,
url: newCompany.url
};
and also you don't need to use $scope.companyData just use newCompany inside your save function
$scope.addCompany = function() {
var company = new Companies($scope.newCompany);
company.$save();
};
if you see in console using console.log(newCompany) after submit data it already there with key value pair as you trying to create with your $scope.companyData

Save an array of objects in angular

Hi I'm trying to put together the next object
$scope.passengers = {
adult : [ {firstname: "name", lastname: "anothername"},{firstname: "name", lastname: "anothername"},{firstname: "name", lastname: "anothername"}],
child : [ {firstname: "name", lastname: "anothername"},{firstname: "name", lastname: "anothername"},{firstname: "name", lastname: "anothername"}],
extras : "someValue"} ;
In my controller I have the following
$scope.passengers = {};
$scope.passengers.adult = [];
$scope.passengers.child = [];
$scope.numberAdult = 10;
$scope.numberChildren = 10;
Y las funciones
//Functions return an array null
$scope.getNumber = function(num) {
num = parseInt(num);
return new Array(num);
};
$scope.savePassengers = function(product_id)
{
//for the moment only print the variable
console.log($scope.passengers)
}
In My HTML page
<form name="passengers-form" ng-submit="savePassengers(product.id)">
<div class="col-lg-12">
<div class="form-horizontal">
<div class="row">
<div class="form-group" ng-repeat="a in getNumber(numberAdult) track by $index">
<label class="col-sm-3 control-label">Adult {{$index + 1 }}</label>
<div class="col-sm-3">
<input required ng-model="passengers.adult[$index].firstname" class="form-control" placeholder="First Name" type="text">
</div>
<div class="col-sm-3">
<input required ng-model="passengers.adult[$index].lastname" class="form-control" placeholder="Last Name" type="text">
</div>
</div>
<div class="form-group" ng-repeat="a in getNumber(numberChildren) track by $index">
<label class="col-sm-3 control-label">Child {{$index + 1 }}</label>
<div class="col-sm-3">
<input required ng-model="passengers.child[$index].firstname" class="form-control" placeholder="First Name" type="text">
</div>
<div class="col-sm-3">
<input required ng-model="passengers.child[$index].lastname" class="form-control" placeholder="Last Name" type="text">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Extras</label>
<div class="col-sm-6">
<textarea name="" ng-model="passengers.extras"class="form-control" id="" cols="30" rows="10"></textarea>
</div>
</div>
<div class="col-xs-9 col-sm-9 col-md-9 col-lg-9">
<div class="form-group buttons pull-right">
<button class="btn btn-primary" id="guardar" type="submit">
<i class="fa fa-save"></i>Add to Cart ->
</button>
</div>
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
</form>
But, when i print the variable "passenger" , the console show : Object {extras: "someValue"}
Your problem is that ng-repeat creates an isolated scope, so your input fields are not reflecting in the correct scope. This can further be verified by your extras field being properly fulfilled.
You should change these lines in your HTML:
<input required ng-model="$parent.passengers.adult[$index].firstname" class="form-control" placeholder="First Name" type="text">
...
<input required ng-model="$parent.passengers.adult[$index].lastname" class="form-control" placeholder="Last Name" type="text">
And do the same thing for the children area.

Controller as vm with ng-click

I am trying to follow John Papa's Angular Style Guide however i cannot get the model data of input file with ngClick.
When i try with $scope everything works just fine.
Here is the Demo on Plnkr.
Glad for your help.
In the ng-model instead of assigning directly to vm, assign it to vm.data and pass vm.data as argument to ng-click like data-ng-click="vm.saveEvent(vm.data)"
<form>
<fieldset>
<div class="form-group">
<label for="eventName">Event Name:</label>
<input id="eventName" type="text" data-ng-model="vm.data.name" placeholder="Name of your event"/>
</div>
<div class="form-group">
<label for="eventDate">Event Date:</label>
<input id="eventDate" type="text" data-ng-model="vm.data.date" placeholder="format (mm/dd/yyyy)"/>
</div>
<div class="form-group">
<label for="eventTime">Event Time:</label>
<input id="eventTime" type="text" data-ng-model="vm.data.time" placeholder="Time of your event"/>
</div>
<div class="form-group">
<label for="eventLocation">Event Location:</label>
<input id="eventLocation" type="text" data-ng-model="vm.data.location.addresss" placeholder="Address of your event"/>
</div>
<div class="form-group">
<input id="eventCity" type="text" class="input-small" data-ng-model="vm.data.location.city" placeholder="City"/>
<input id="stateProvince" type="text" class="input-small" data-ng-model="vm.data.location.province" placeholder="Province"/>
</div>
<div class="form-group">
<label for="eventImageUrl">Image:</label>
<input id="eventImageUrl" type="text" class="input-xlarge" data-ng-model="vm.data.imageUrl" placeholder="Url of image"/>
</div>
</fieldset>
{{vm.data.name}}
<img data-ng-src="{{vm.data.imageUrl}}"/>
<br/>
<br/>
<div class="form-group">
<button type="submit" class="btn btn-primary" data-ng-click="vm.saveEvent(vm.data)">Save</button>
<button type="button" class="btn btn-default" data-ng-click="vm.cancelEvent(vm.data)">Cancel</button>
</div>
</form>
Controller:
eventsApp.controller('EditEventController',
function EditEventController() {
var vm = this;
this.data = {};
vm.saveEvent = saveEvent;
function saveEvent(event) {
window.alert("event" + event.name + ' saved');
console.log(vm.data);
}
//vm.saveEvent = function(event) {
// window.alert("event" + event.name + ' saved');
//};
}
);
http://plnkr.co/edit/AxdA7vc70aTw3RojofVY?p=preview
ng-click="vm.saveEvent(vm.data)" did not work for me with Angular 1.4.
My solution was to use the control variable name.
e.g. "LoginController as loginctrl" so <button ng-click="loginctrl.doLogin()">Login</button>
Then in my control I was able to use this for the doLogin function inside my LoginController:
/* #ngInject */
function LoginController() {
/*jshint validthis: true */
var vm = this;
vm.title = 'Login';
function doLogin() {
...
}

Reset form after submission in AngularJS

I'm having trouble resetting form fields after submitting in AngularJS (v1.1.3). Here's a snippet of what I'm trying to do:
HTML
<form name="addMemberForm">
<input name="name" type="text" placeholder="Jon Doe" ng-model="member.name" required/></td>
<a class="btn btn-primary" ng-click="createMember(member)" ng-disabled="addMemberForm.$invalid"><i class="icon-plus"></i></a>
</form>
JS
$scope.createMember = function(member) {
var membersService = new Members(member);
membersService.$create(function(member) {
$scope.members.push(member);
$scope.addMemberForm.reset(); //TypeError: Object #<FormController> has no method 'reset'
});
};
Is there another way to reset form elements?
Figured it out thanks to #tschiela's comment. I had to do this:
$scope.createMember = function(member) {
var membersService = new Members(member);
membersService.$create(function(member) {
$scope.members.push(member);
$scope.member = '';
});
};
Just Take default value of the form .
HTML form
<form novalidate id="paperForm" class="form-horizontal" name="formPaper">
<div class="form-group">
<label class="col-sm-3 control-label" for="name">
Name
</label>
<div class="col-sm-8">
<input type="text" id="name" placeholder="Please Enter Name" class="form-control" ng-model="paper.name" ng-name="name" required>
</div>
<label class="col-sm-3 control-label" for="name">
Department
</label>
<div class="col-sm-8">
<input type="text" id="department" placeholder="Please Enter Department" class="form-control" ng-model="paper.department" ng-name="department" required>
</div>
</div>
<button type="button" class="btn btn-default" ng-click="reset(paper)">Reset</button>
</form>
set reset code inside controller
var deafualtForm = {
name : '',
department : ''
}
$scope.reset= function(paper) {
$scope.paper = angular.copy(deafualtForm);
}

Categories

Resources