How to put form data into json file in angularjs - html

I am creating an application where I have to add the contacts from a form input. I want to add data from the form input field to my JSON file.
Unfortunately I am not able to find any solution for it until now. Kindly help in this regard. This is my controller code where the JSON object is also defined. I want to fetch the data from input filed to the JSON object array.
var contactManager = angular.module('contactManager', ['ngAnimate']);
// Contacts List Controller
contactManager.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/data.json').success(function(data) {
$scope.contacts = data;
//$scope.contacts = 'name';
});
}]);
// Contacts Details Controller
contactManager.controller('DetailsController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$scope.contact = [{
"name": "Stephen Radford",
"phone": "0123456789",
"address": "123, Some Street\nLeicester\nGH1 2SR",
"email": "stephen#email.com",
"website": "stephenradford.me",
"notes": ""
},
{
"name": "Alan Border",
"phone": "154648445",
"address": "457, Some Street\nBirmingham\nLM1 2AB",
"email": "stephen#email.com",
"website": "alanborder.me",
"notes": ""
},
{
"name": "Misbah ul Haq",
"phone": "8899556744",
"address": "458, Some Street\nFaisalabad\nFD1 2MH",
"email": "misbah#email.com",
"website": "misbah.me",
"notes": ""
}
];
$scope.contactId = $routeParams.contactId;
$scope.addNew = function() {
$scope.contact.push($scope.newData);
$scop.newData = null;
$scope.added = true;
};
}
]);
This is my form code. Where I am taking the input from a form
<form class="form-horizontal" ng-submit="addNew()" ng-controller="DetailsController">
<input ng-model="contact.name">
<input ng-model="contact.phone">
<input ng-model="contact.address">
<button>Click here to store data</button>
</form>

You need to send the object to data storedata function.
<button ng-click="storedata(obj)">Click here to store data</button>
Than, you can do it whatever you want.
$scope.storedata = function(obj) {
// obj is json
$post('/path_to_server', obj);
};

Related

Add value of key that will be pushed to an array Angular

The value inside the input and textarea should be pushed the entire JavaScript part works, but how can I bind the ng-model so that Angular will pick up the value of entered information and push that into an array. Anyone an idea how to do that in HTML.
angular.module("forum-page", ["myApp"])
.controller("Forum", function($scope) {
$scope.comments = [
{
"name": "Kevin",
"comment": "Wat een mooi toestel vandaag ontvangen, zeer blij met mijn bestelling :)",
"country": "Nederland"
},
{
"name": "Jason",
"comment": "What a great phone I received from Meizu, will surely come back to buy again in the future",
"country": "USA"
},
{
"name": "姚宣辰",
"comment": "這個手機很標亮, 下次也會買魅族智能手機",
"country": "中国"
},
];
$scope.addComment = function() {
$scope.comments.push({ "name": $scope.name, "comment": $scope.comment, "country": $scope.country});
var dataObj = {
name: $scope.name,
comment: $scope.comment,
country: $scope.country
};
$scope.dataObj = dataObj;
res.error(function(data, status, header, config) {
alert("failure message: " + JSON.stringify({data: data}));
});
$scope.name = "";
$scope.comment = "";
$scope.country = "";
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<input type="text" class="comment-box-name" ng-model="{{dataObj.name}}"/>
<input type="text" class="comment-box-comment" ng-model="{{dataObj.comment}}"/>
<textarea type="text" class="comment-box-country" ng-model="{{dataObj.country}}"></textarea>
<button ng-click="addComment()">Place comment</button>
No you cannot do that if you want that kind of automation in the template. In order to do that kind of action you need to place that action inside your click event listener which acts as the send button.
$scope.addComment = function () {
// Add validations before proceeding
theArray.push(dataObj);
}
Hope that helps
Some changes needed in your code :
1. remove {{}} from the ng-model value.
use dataObj.name,dataObj.comment,dataObj.country instead of {{dataObj.name}},{{dataObj.comment}},{{dataObj.country}}
2. use $scope object instead of var to initialize the object to perform the two way data binding.
$scope.dataObj = {
name: $scope.name,
comment: $scope.comment,
country: $scope.country
};
Demo!

Displaying JSON data with ng-bind shows [object object]

I'm new to angular js,I have 2 goals:
OnClick, display a single person's name from a JSON array,
Randomize name on every click
I'm stuck at the part where i need to pass the json data to the view: when i click the button i get [object object], [object object], [object object]
Could someone please assist?
[
{"name": "John"},
{"name": "Sue"},
{"name": "Sally"},
{"name": "Jim"},
{"name": "Bev"},
{"name": "Joe"},
{"name": "Jess"}
]
script
var peopleApp = angular.module('peopleApp', []);
idApp.controller('peopleCtrl', ['$scope', '$http', function ($scope, $http){
$scope.randomPerson = function(){
$http.get('js/people.json').
success(function(data) {
$scope.person = data;
console.log(data);
});
}
}]);
view
<div class="content">
<div ng-controller="peopleCtrl">
<p ng-bind="name"></p>
<button ng-click="randomPerson()">
Show random person's name
</button>
<p ng-bind="person"></p>
</div>
</div>
You need to show a simple value after to get a random object of your array.
Something like this:
var peopleApp = angular.module('peopleApp', []);
peopleApp.controller('peopleCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.data = [{
"name": "John"
}, {
"name": "Sue"
}, {
"name": "Sally"
}, {
"name": "Jim"
}, {
"name": "Bev"
}, {
"name": "Joe"
}, {
"name": "Jess"
}];
$scope.person = "";
$scope.randomize = function(count) { // This function returns a random number, between 0 to the $scope.data.length.
return Math.floor((Math.random() * count) + 0);
};
$scope.randomPerson = function() { // By using array.filter you can get a specific object.
$scope.person = $scope.data.filter(function(x) {
return x.name;
})[$scope.randomize($scope.data.length)]; // Getting the random object.
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="peopleApp" class="content">
<div ng-controller="peopleCtrl">
<p ng-bind="name"></p>
<button ng-click="randomPerson()">
Show random person's name
</button>
<p data-ng-bind="person.name"></p>
</div>
</div>
More simpler and better: Without using array.filter.
var peopleApp = angular.module("peopleApp", []);
peopleApp.controller("peopleCtrl", ["$scope", "$http",
function($scope, $http) {
$scope.data = [{
"name": "John"
}, {
"name": "Sue"
}, {
"name": "Sally"
}, {
"name": "Jim"
}, {
"name": "Bev"
}, {
"name": "Joe"
}, {
"name": "Jess"
}];
$scope.person = "";
$scope.randomize = function(count) { // This function returns a random number, between 0 to the $scope.data.length (count).
return Math.floor((Math.random() * count) + 0);
};
$scope.randomPerson = function() {
$scope.person = $scope.data[$scope.randomize($scope.data.length)]; // Getting the random object.
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="peopleApp" class="content">
<div ng-controller="peopleCtrl">
<p ng-bind="name"></p>
<button ng-click="randomPerson()">
Show random person's name
</button>
<p data-ng-bind="person.name"></p>
</div>
</div>
The reason this is happening is because you are sending an array of objects from the controller to your view.
And then you directly bind the array to a <p> tag. So the entire array is getting displayed with object as it is unparsed on your view..
try changing
<p ng-bind="person"></p>
To :
<p ng-bind="person[randomIndex].name"></p>
// here random index is a random number
// where range of random number generator is from 0 to length of person array
you can generate a random number on click of function like this. If you wanted to get between 0 and length of array, you would put:
Math.floor(Math.random() * person.length) + 0
OR More specifically something like this ....
$scope.randomPerson = function(){
$http.get('js/people.json')
.success(function(data) {
$scope.person = data;
var randomPersonIndex =Math.floor(Math.random() * $scope.person.length) + 0 ;
$scope.myRandomPerson = $scope.person[randomPersonIndex];
console.log(data);
});
And then on HTML you do ....
<p ng-bind="myRandomPerson.name"></p>
// here random index is a random number
Simple and easy just need to add "| json" with your function name.
for example
<p ng-bind="person | json"></p>

AngularJS display JSON data in table

I am using AngularJS with RESTAPI, I am able to get the customers data sent from server in a JSON format. My Angular code snippet as below:
app.factory("services", ['$http', function($http) {
var serviceBase = '/api/album';
var obj = {};
obj.getCustomers = function(){
return $http.get(serviceBase);
};
return obj;
}]);
app.controller('listCtrl', function ($scope, services) {
services.getCustomers().then(function(data){
alert(JSON.stringify(data.data));
$scope.customers = data.data;
});
});
Here is my JSON data:
{
"data": [
{
"id": "1",
"artist": "Gotye75",
"title": "Making Mirrors7"
},
{
"id": "100",
"artist": "ytttt5",
"title": "1231"
},
{
"id": "101",
"artist": "65",
"title": "565444555"
},
{
"id": "102",
"artist": "6",
"title": "6"
},
{
"id": "103",
"artist": "y",
"title": "yy"
},
{
"id": "104",
"artist": "ty",
"title": "yt"
},
{
"id": "109",
"artist": "ytrer",
"title": "yt"
}
]
}
I am able to display the JSON data in table if my JSON does not contain the "data" hear. However if my jSON data comes with "data" header, it is unable to display. I am asking, what are the solution in Angular to parse the JSON object.
For example if it is in BackboneJS, i can simply do
parse: function (response) {
//alert(JSON.stringify(response.data));
return response.data;
}
How can i do it in Angular?
$http resolves its promises with a response object. The data is accessed via the response object's data property. So to get to the array, you'd have to use
$scope.customers = data.data.data;
$http's promise is enhanced with a .success() convenience method which unwraps the response object...
services.getCustomers().success(function(data){
alert(JSON.stringify(data.data));
$scope.customers = data.data;
});
I solved it by
app.controller('listCtrl', function ($scope, services) {
services.getCustomers().then(function(data){
//notice that i added the third data
$scope.customers = data.data.data;
});
});

How to get deeper in a JSON object using angularJS?

I am using AngularJs to get some information inside this JSON object, specifically the author's first and last name:
{
"bookid": "1",
"title": "Spring In Action",
"publisher": "Manning Publications Co.",
"isbn": "978-1-935182-35-1",
"owner": "Catalyst IT Services",
"publishyear": "2011",
"image": "C:/imagefolder/spring-in-action.jpg",
"description": "Totally revised for Spring 3.0, this book is a...",
"author": [
{
"authorid": "1",
"firstname": "Craig",
"lastname": "Walls",
"description": "Craig Walls has been professionally developing software for over 17 years (and longer than that for the pure geekiness of it). He is the author of Modular Java (published by Pragmatic Bookshelf) and Spring in Action and XDoclet in Action (both published by (...)"
}
],
"media": [
],
"tags": [
{
"tagid": "1",
"tagname": "Java"
},
{
"tagid": "5",
"tagname": "Spring"
}
],
"copies": [
{
"bookcopyid": "2",
"location": "Beaverton",
"status": "available"
}
]
}
The code I have right now is (which was provided by bosco2010 in this plunker (http://plnkr.co/edit/GbTfJ9)):
var app = angular.module('app', []);
app.factory('JsonSvc', function ($http) {
return {read: function(jsonURL, scope) {
return $http.get(jsonURL).success(function (data, status) {
scope.data = data.author;
});
}};
});
app.controller('MainCtrl', function($scope, JsonSvc) {
JsonSvc.read('data.json', $scope).then(function () {
$scope.nestedObj = $scope.data;
});
$scope.name = "world";
});
To get the first and last name, you'll need to reference author[0].firstname and author[0].lastname.
var app = angular.module('app', []);
app.factory('JsonSvc', function ($http) {
return {read: function(jsonURL) {
return $http.get(jsonURL);
}};
});
app.controller('MainCtrl', function($scope, JsonSvc) {
// The return object from $http.get is a promise. I used .then()
// to declare $scope.nestedObj after the http call has finished.
JsonSvc.read('data.json').then(function (data) {
console.log(data.data);
$scope.nestedObj = data.data.level1;
});
// ensure app is working
$scope.name = "world";
// Using nested obj within declared scope var doesn't work
// Uncomment below to break whole app
// Using nested obj in a function works but throws TypeError
// Declaring $scope.data.level1.level2 = [] first helps here
$scope.getLen = function () {
return $scope.nestedObj ? $scope.nestedObj.level2.length : ''; // return an empty string if the callback didn't happen yet
};
});
In short, it is incorrect to use both the success() function and also the then() function of the promise returned by the $htttp service.
Moreover, it is wrong to pass your scope as a parameter to your service and try to modify it there.
if you need to communicate between the service and a controller directly, you can use either $rootScope, $broadcat, or both.
I patched up your code, and now it works.
Plunk:
http://plnkr.co/edit/PlJZZn?p=preview

How to receive a json string after a jquery post in WebMatrix?

If I have the following post call:
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"uno": "lalala",
"dos": "jojojo"
}
var data = JSON.stringify(datos);
$.post(url, data, function (resultado) {
$('#posted_values').html(resultado);
});
});
How can I receive and process the json object in a cshtml file? I mean what I put in Decode call:
if (IsPost)
{
var json_object = Json.Decode(Request???);
}
Edited to complete the answer of #MikeBrind, to help others with the same problem.
Example of using decode for a more complex json object.
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumber": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
var data = JSON.stringify(datos);
$.post(url, {"person": data}, function (resultado) {
$('#posted_values').html(resultado);
});
});
Receiving and using:
#{
dynamic json_object;
if (IsPost)
{
json_object = Json.Decode(Request["person"]);
#json_object.firstName<br/>
#json_object.lastName<br/>
#json_object.address.city<br/>
#json_object.address.postalCode<br/>
foreach (dynamic phone in json_object.phoneNumber)
{
#phone.type<br/>
#phone.number
}
}
}
Don't JSON.stringify the data if it is just key/value pairs like this. Do a form post:
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"uno": "lalala",
"dos": "jojojo"
}
//var data = JSON.stringify(datos); no need for this
$.post(url, datos, function (resultado) {
$('#posted_values').html(resultado);
});
});
Then the values are available from Request["uno"] and Request["dos"]
If you ever do need to use JSON.stringify (which you would for more complex data structures), the JSON is transmitted in the Request body, so you need to extract it from Request.InputStream:
var reader = new StreamReader(Request.InputStream);
var json = reader.ReadToEnd();