Angulajs - how to extract certain data from json - angularjs

I have this json example where I need to get data individually.
json:
[
{
"web": "63",
"mobile": "2525",
},
{
"web": "70",
"mobile": "1886",
},
{
"web": "65",
"mobile": "1044",
}
]
then in the controller:
myData.get ().then (function (data) {
$scope.data = data;//this is fine
console.log(data);
$scope.web = data.web//this does not work
$scope.mobile = data.mobile//this does not work
console.log($scope.data.web);//this does not work
console.log($scope.web);//this does not work
//and then lets say I want to pass them in the url
var myUrl = "www.myurl.com/"+$scope.web+$scope.mobile;
});
so basically I need to be able to work with individual data within the json file, so I can pass them them anywhere within the applications logic. What am I doing wrong?
heres plunker: http://plnkr.co/edit/Dre5j8yLDoJek89KCmak?p=preview
Many thanks for your help

You need to use the data object inside $scope. So, if you try the following, it should work properly. console.log($scope.data) or console.log($scope.data.web)
In your controller, define an empty array and then assign the response to it.
var localdata = [];
// http call goes here
localdata = response.data;
// access the required members of localdata array
// since it's an array, you need to access individual data elements with index
// for example:
console.log($scope.data[0].web)

Use
$scope.data = angular.fromJson(data);
console.log($scope.data);
and check

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/

In AngularJS, $http doesn't change my select option tag data

I have an issue in AngularJS on using $http to fetch data from server.
Here is my HTML
<select ng-model="foo" ng-options="item as item.name for item in items"></select>
Here is my AngularJS Script
angular.module("myApp").controller("myCtrl", function($scope, $http) {
var $scope.items = [];
$scope.items = [
{
"id": 1,
"name": "item1"
},
{
"id": 2,
"name": "item2"
},
];
getData();
function getData() {
$http.get("ng/getData")
.then(function(response) {
if (response.status == 200) {
$scope.items = response.items;
/*
$scope.items = [
{
"id": 5,
"name": "item11"
},
{
"id": 4,
"name": "item22"
}
];
*/
}
});
}
});
What expect from this code is when $http fetches data from server, then select dropdown data will change. But it's not changing anything. I have also printed the response items in the console inside the success callback.
Maybe I don't understand $http usage well enough. Perhaps when I console out data after getData(); $scope.items doesn't change at all. And I think that maybe $http always run at last stage.
Can anybody help to explain this issue? If my assumption is correct, what is the solution that I am looking for?
I think you simply have to add a track by clause:
ng-options="item as item.name for item in items track by item.id"
Check the response object. When you are using 'then' callback to get the resolved data then the actual API result is stored in the 'data' property of the response. So change your code to
$scope.items = response.data;
Or you can use the success callback to attach the data directly.
$http.get("ng/getData")
.success(function(response) {
if (response.status == 200) {
$scope.items = response.items;
}
});

setting the scope value after the http call in Angularjs

I have a controller in which I make an ajax call. In the success callback I assign some value to $scope variable like below.
$http.get(GlobalService.getDomainUrl() +'/hosts/attr').success(function(data){
//Now that we have made the ajax call we need to first get all the config values..
$scope.classifications = _.allKeys(data);
var config;
_.each(data, function(e) {
$scope.config = _.allKeys(e);
console.log($scope.config);
_.each(config, function(attr){
$scope.attributes = attr;
});
});
});
The data from the server is in the below format:
{
"my_config": {
"cpu": [
"2"
],
"mem": [
"4GB"
]
},
"network_config": {
"my_config": [
"ON",
"OFF",
"NONE"
],
"os_config": [
"LINUX",
"MS",
"OSX"
]
}
}
Inside my html code:
<div class="row">
{{config}}
</div>
When I try to use the values in my html file using {{config}} I am seeing an empty array. On the browser console I am able to see the data since I am printing using console.log statement. Please let me know where I am going wrong.
The issue got resolved. The $scope.config was getting set correctly but since the last item in the array returned from the server was empty that was overwriting the value of the scope.config.

Angular Factory Manipulating Data (CRUD) with function in the Factory

I have a simple Angular App that uses a factory to pull a list of items from a "JSON" file. Eventually this will be connected to a database but for now I'm starting with just pulling from a static file. The JSON file contains an array of items. I'm really trying to understand how do I get a reference to my data in the factory after the promise has been returned to the controller.
My Factory is setup as follows:
angular.module("myApp").factory("ServiceTypeFactory", ['$http', function ($http ) {
return {
ServiceTypes: function () {
return $http.get('json/servicetypes.json').success
(
function (data) {
return data;
});
},
find: function (id) {
return _.findWhere(data, {ID:id}); // Not sure how to get access to the data
}
}
}]);
This works great I can share the Factory across multiple controllers. The part I'm missing is how do I reference a specific array item from my json file and update it in my controller. I'm not following how to get a reference to the actual data so when I modify the item in one controller it the change would be reflected in another controller.
In both of my controllers I have the following code to get a reference to the data initially.
var popService = function (data) {
$scope.ServiceTypes = data;
}
// IF at ANY time the Service Types have not been loaded we will populate them.
if (typeof $scope.ServiceTypes === "undefined") {
ServiceTypeFactory.ServiceTypes().success(popService);
}
My understanding is my $scope.ServiceTypes has really a reference to the data. How do I back in my factory in a function get access to the actual single source of my data. I get that the factory returns the data with functions an object but I'm missing how to reference this data back in my factory to manipulate it. In the future I want to perform CRUD operations on it for the time being I'm just trying to work out the mechanics.
What my JSON file looks like:
{
"serviceTypes": [
{
"ID": "1001",
"ServiceTypeName": "111111",
"Description": "aaaaaaa"
},
{
"ID": "1002",
"ServiceTypeName": "222222",
"Description": "bbbbbbb"
},
{
"ID": "1003",
"ServiceTypeName": "3333333",
"Description": "ccccccc"
},
{
"ID": "1004",
"ServiceTypeName": "444444",
"Description": "dddddddd"
},
{
"ID": "1005",
"ServiceTypeName": "5555555",
"Description": "eeeeeee"
}
]
}
Just needed to clean the code up a little. Watching a couple of quick example on egghead.io made it clear.

Resources