I want to Pass value to JSON in angularjs - angularjs

Please give me some example of $http.post. I am new in AngularJS. I want to update a JSON file while retrieving information from user. I want to update values but unable to update a JSON file.
My JSON file is data.json.
{ var app=angular.module("APP",[]);
app.controller("APPController", function ($scope, $http){
$scope.add = function(){
var dataObj={ model:$scope.addModel,
car: [$scope.option1, $scope.option2, $scope.option3, $scope.option4],
type: $scope.Type};
$http.post("data.json",dataObj)
.success(function(res){console.log("success"+res.records)}) .error(function(res){console.log("error")});
};
});
}
and here is my data.json file
{
"records": [
{
"model" : "car model",
"car" : ["num1","num2","num3","num4"],
"type" : "mode type"
},
{
"model" : "car model",
"car" : ["num1","num2","num3","num4"],
"type" : "mode type"
},
]
}

You can pass the data object in 2nd param of the $http.post() method.
I am confused to get the exact context of update JSON. But if you want to update the existing variable array in your controller which you are using in view from the response, you can do it it JavaScript way.
Here is a working example for the same. This might help.
JSFiddle: http://jsfiddle.net/ashishanexpert/zvcx5z38/2/

You don't POST data on a JSON file, you make the POST API call to a server.
You can GET data from a JSON file.
I suggest you read through Angular's POST documentation first.

Related

update the json after delete some data inside it

I try to learn angular. currently, i already get data from JSON ( i use local JSON). I try to delete 1 of an array from JSON, its works but after I refresh the page the deleted array come back again. how to update the JSON after I delete array?
customer.html
<tr ng-repeat="experience in experiences">
<td>{{experience.no}}</td>
<td>{{experience.name}}</td>
<td><button ng-click="deleteItem(experience)" class="btn btn-danger">-</button></td>
</tr>
main.js
resolve:{
experiences:['$http',function($http){
return $http.get('scripts/customer.json').then(function(response){
return response.data
})
}]
}
customer json
[
{
"no":1,
"name": "Sarah",
},
{
"no":2,
"name": "Tommy",
}
]
customerCtrl.js
angular.module('app').controller('customerCtrl',['$scope','experiences',function($scope,experiences){
$scope.experiences= experiences;
$scope.deleteItem =function(experience){
var index = $scope.experiences.indexOf(experience);
alert("Deleting DATA: "+ index);
$scope.experiences.splice(index,1);
};
}]);
You're trying to store data in a file using javascript, which is considered as insecure and then hard to implement.
I would suggest you to use LocalStorage instead. Here is a service example you could use in your controller (not tested)
localstorage service
angular.module('app').service('LocalStorage', function(){
return {
save: function(data) {
localStorage.setItem('data',data);
},
get: function(){
return localStorage.getItem('data');
}
};
});
controller
// notice that I injected LocalStorage in controller
angular.module('app').controller('dataPengalamanCtrl',['$scope','experiences',function($scope,experiences, LocalStorage){
$scope.experiences= experiences;
$scope.deleteItem =function(experience){
var index = $scope.experiences.indexOf(experience);
alert("Deleting DATA: "+ index);
$scope.experiences.splice(index,1);
// First transform you're json to a string
var stringifiedData = JSON.stringify( $scope.experiences);
// from there we save data to localStorage
LocalStorage.save(stringifiedData );
};
// if you need, you can load data using :
$scope.data = LocalStorage.get();
Dont forget to save your json in localstorage first, for example with a file like this one :
init.js
var json = [
{
"no":1,
"name": "Sarah",
},
{
"no":2,
"name": "Tommy",
}
];
var strData = JSON.stringify(json);
localstorage.setItem('data', strData);
EDIT
If you want to go with a remote server like myjson.com
Assuming you already saved your json on myjson.com, and url is https://api.myjson.com/bins/8hghd then :
To retrieve your json use $http.get('https://api.myjson.com/bins/8hghd').success(/*...*/).error(/*..*/);
To update your json use $http.put with your json as data (grammar depending of your AngularJS version, see here)
Have a look to the api documentation : http://myjson.com/api

How can i use JSON stringify in Angular?

i'm newbie to Angular. I'm trying to get Json data which written like that :
id:1,
name: "Friends",
type: "Group",
Now, i know i can't use this kind of data unless i add double quotes - like that (it's the only way it is working):
"id":1,
"name": "Friends",
"type": "Group",
What is the best way to parse JSON in Angular?
I've tried to combine JS , but it didn't work :
app.controller('contacts', function ($scope,$http,$log) {
$http.get('http://localhost/Angular-Http-exercise/db.json')
.then(function(response) {
$scope.myData = function() {
return JSON.stringify(response.data)
};
$log.info(response.data.name);
});
});
You can use angular.fromJson and angular.toJson for that purpose:
scope.myData = function(){
return angular.fromJson(response.data);
}
However JSON is a global variable and you should have access to it, since angular uses the same.
https://docs.angularjs.org/api/ng/function/angular.fromJson
https://docs.angularjs.org/api/ng/function/angular.toJson
Roy, your question is What is the best way to parse JSON in Angular? JSON will not differ from one framework/language to another and there's no best way to write JSON.
If you want to see if your JSON is formatted correctly check out tools like: https://jsonformatter.curiousconcept.com/

Access to nested object in JSON ,select the right value in a dropdownlist (Angularjs)

I am a beginner in AngularJS. I used the $resource service to get a specific object of type person based on its id from the server in order to update this object.
Resource service:
moduleName.factory('Person', function ($resource) {
return $resource('/application/person/:id', {}, {
show: { method: 'GET' , params: {id: '#id'}},
});
});
The object that I received and it displayed in my browser using the {{}} is:
{
"id": "560cf96ee85532035928889e",
"firstName": "Christiane",
"gender": "Male",
"flight": {
"id": null,
"arrivalDate": "2015-01-05 11:30",
"arrivalAirport": {
"name": "Frankfurt"
},
"stopovers": []
}
}
In this form I have a dropdownlist that contains the Airport list, I expect that the value of the arrivalAirport will be selected in this dropdown list, but no value was selected, I try to set the selected value of this dropdown list in the AngularJs controller of this view.Before setting the value of this object I try to access to their value by this code inside the controller.
moduleName.controller('PersonDetailController',function ($scope, $routeParams, Person,$location) {
$scope.person = Person.show({id: $routeParams.id});
console.log($scope.person.flight.arrivalAirport);
});
when I want to get the value of the object flight.arrivalAirport nested in person object I got this error.
TypeError: Cannot read property 'arrivalAirport' of undefined
How can I display the right value selected in the dropdown list and how can I access to the other object like stopovers array in order to update their values?
Thank you.
When you call console.log Person's data hasn't been retrieved yet. You should do something like this:
$scope.person = Person.show({id: $routeParams.id}, function(person) {
console.log(person.flight.arrivalAirport);
});
In general, any code working on data received asynchronously can't be put right after the call because it's very unlikely that data has been retrieved at that point, you should use callbacks and promises.
Your view should update automatically, and you said it does, at least for the part showing the json. In order to make the dropdown update you should bind its values to a property inside $scope.person
If the dropdown doesn't update then there must be some other error and you might need to post the dropdown's code too.
If you want to manually update the dropdown's list instead then you need to put the relevant code inside the callback (the function i added to "person.show" in the code above) in order to make it work

angularjs + jsonp returns a fail

I am trying to build a sample app that will grab data using JSONP to populate. I have it put up at http://angular.onagrag.com/ and clicking on register.
The file I am trying to load is at http://api.onagrag.com/data.json
When I access http://angular.onagrag.com/register it fires the error method of the object (and it fires it twice)
here is the angular js file that I am using (it is also located at http://angular.onagrag.com/js/test.js
It runs fine if I use local data (e.g. use the $http.get method instead of the $http.jsonp method), but will not work with jsonp. Any help is appreciated!
var App = angular.module('popdust', ['ngResource']).config(['$locationProvider', function($location) {
$location.html5Mode(true).hashPrefix('!')
}]);
App.config(['$routeProvider', function($routes) {
$routes.when('/register',{
templateUrl : '/templates/register.html',
controller : RegisterCtrl
});
$routes.when('/',{
templateUrl : '/templates/home.html',
controller : HomeCtrl
});
}]);
var HomeCtrl = function($scope, $http, $location) {
$scope.title = 'We are home';
$scope.obj = ['one', 'two','three'];
};
var RegisterCtrl = function($scope, $http, $location) {
$scope.title = 'Register!';
$scope.handleData = function(data){
$scope.fields = data;
}
$scope.fetchjsonp = function(){
$http.jsonp('http://api.onagrag.com/data.json?callback=JSON_CALLBACK').success(function(data){
alert("success");
}).error(function(data, status, headers, config) {
alert("YOU FAIL");
});
}
$scope.fetch = function(){
$http.get('js/data.json').success($scope.handleData);
}
$scope.fetchjsonp();
};
HomeCtrl.$inject = ['$scope','$http','$location'];
RegisterCtrl.$inject = ['$scope','$http','$location'];
Looks to me like the problem is with your resource. When I check http://api.onagrag.com/data.json?callback=JSON_CALLBACK I get the following response:
[{
"id" : "first_name",
"title" : "First Name",
"description" : "The name your parents gave you"
},{
"id" : "last_name",
"title" : "Last Name",
"description" : "In Spanish, it's called your apellido (or something like that)"
}]
This is not a valid JSONP response. With the request parameter callback=nameOfCallbackFn the response should be a single function call to a function named nameOfCallbackFn (with the result as it's only parameter).
Update: The server that serves the JSONP must read the callback request parameter and respond with a file that does a method call to the request method name. When you use the angular $http.jsonp method, angular will change the callback request parameter to the correct angular jsonp callback method name (atm they seem to be named angular.callback._0, ..._1 etc). You can't serve a static file as this name might change from one request to the other. This was not clear in my original answer.
Something like this:
nameOfCallbackFn ( [{
"id" : "first_name",
"title" : "First Name",
"description" : "The name your parents gave you"
},{
"id" : "last_name",
"title" : "Last Name",
"description" : "In Spanish, it's called your apellido (or something like that)"
}] );
Where nameOfCallbackFn is specified by angular.
JSONP has some potential security vulnerabilities - you can read more about them and how to prevent them in your angular app here.

Backbone Model not compatible with underscore and ASP.NET MVC Web API Controller?

This is a two stage problem when working with backbone.js and a web api controller.
I have a simple web api controller that returns a JSON string, in fiddler the result looks like this:
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading":"The heading"
}
I use the following code to fetch a user from my web api
var user = new Usermodel({ id: "1" });
user.fetch({
success: function (u) {
console.log(u.toJSON());
}
});
now my backbone user object looks like this
{
id: "1",
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading": "The heading"
}
}
When I try to bind this backbone model object to my view template that looks like this
<form>
<input type="text" value="<%=Heading%>" />
<input type="submit" value="Save" />
</form>
i get, Heading is undefined but when I use id it binds just fine? It seems like underscore does not like the backbone model object and just want a plain JSON object just like the one I get from my web api?
The second problem with this is that when I save my model with user.save({ Heading: "my new heading }); the payload to my web api is the backbone model which is completely wrong because my api expects a user object like this to be sent to the server:
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading":"The heading"
}
and not the backbone model with the real object wrapped inside. Is it possible to solve so that underscore can handle backbone models and tell backbone to only send the payload that my end point expects?
You may be able to solve the problem by following these steps:
In addition to using fiddler to inspect your response, look at the response on the network tab of Chrome Developer Tools. If the response does not look like this, then your web api is not returning a valid json response, the problem is most likely within your web api. You need to get/provide more information about your web api to solve the problem. Verify that the response looks like this:
After verifying that the response from the web api is correct, check out the following jsfiddle I modified:
http://jsfiddle.net/J83aU/23/
Fix your client side code referencing the example I have provided.
Properly instantiate the Backbone objects.
Call the view.render function at the correct step, after the response is received from the server.
Make sure that the main content div is actually rendered before creating a view which depends on it for the 'view.el' property.
Declare the 'view.el' property properly, with a string rather than jQuery object.
Use development Backbone and underscore to enable debugging, an important concept when learning to use open source frameworks such as Backbone.
Use jsfiddle's echo/json api to mock a valid ajax json response, exactly as described in step 1.
The following json example you submitted is not even valid json, if you update your question with valid json example, it would be easier to solve the problem. It is unlikely that Backbone created this non-json structure and more likely that you have submitted it here incorrectly.
{
id: "1",
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading": "The heading"
}
}
Finally, try to provide a screenshot of the http headers or something for the problem that is occurring when you call model.save().
Read over the Backbone documentation for model.save() and make sure you are doing everything just as the example provided.
You may be able to workaround Backbone's funky save function by forcing your attributes into POST parameters using ajax options:
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var saveView = Backbone.View.extend({
events:{
'click #saveSubmitButton':'submit'
},
submit:function (event) {
event.preventDefault();
var view = this,
attributes = $('#saveForm').serializeObject();
this.model.save(attributes, {
data:attributes,
processData:true,
success:function (model) {
//....
}
});
},
render:function () {
//.......
}
});
The attributes property of your model should be unaltered. Send those to your template call:
var MyModel = Backbone.Model.extend();
var newModel = new MyModel({
"$type": "MvcApplication.Models.Article, MvcApplication",
"Heading":"The heading"
});
var html = _.template(templateVar, newModel.attributes);
In your templateVar, which is your templated markup, you should be able to reference $type and Heading directly.
If you have a look at the jsFiddle through a debugger like Firebug you can see that the way you construct the model's URL is not working out, because the forward slash gets encoded. Can you try to modify your model declaration to this:
var Usermodel = Backbone.Model.extend({
url: function () {
return '/api/page/articles/' + this.get('id');
}
});
var user = new Usermodel({
id: '85'
});
And see if you still get the same JSON. Basically if you don't have a Backbone.sync override you are using built-in retrieval that for one shouldn't produce invalid JSON.

Resources