http json file retrieving with IONIC and AngularJS - javascript

I am working on an product reviewing app based on ionic framework.
The app will consume REST service in JSON format.
Because Im not able to retireve data directly from the locally deployed website, i created a json demo file:
[{
"index": 0,
"marque": "labore",
"estAutorise": 0,
"name": "Jennifer Simmons"
},
{
"index": 1,
"marque": "duis",
"estAutorise": 0,
"name": "Beatriz Hale"
},
{
"index": 2,
"marque": "pariatur",
"estAutorise": 1,
"name": "Richmond Garner"
}
]
here is my services.js:
angular.module('starter.services', [])
.factory('Recettes', function($http) {
var recettes = [];
var produits = [];
$http.get('test.json').success(function(data) {
alert("success"); //to check the seccess responce
produits= data;
});
return {
...
produits: function() {
return produits;
},
....
Before this, I implemented products and recettes directly and it works just fine. And now, I recieve the success alert but the data seems to be invalid.
My controller:
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope, Recettes) {
$scope.produits = Recettes.produits();
})
...
So my question is how can i fix the data binding problem ?
And If it works with .json file should it work for rest services as well (Content-Type: application/json )?
Thank you.

Related

How to pass the array object in $http.get method in angularjs

I want to pass Array object in $http.get(). Previously all information is stored in data.json file, But I don't want to use file. Want to define the Array of object as $scope.data in controller.
Please find DEMO
http://plnkr.co/edit/X5ZC3UGey4Zjos7W01U1?p=preview
Working DEMO http://plnkr.co/edit/o6EeKnC8oFEq3GCRsQgp?p=preview
here we are using data.json. I want to define data inside data.json in Controller, Plz tell me how to dd
.controller('QuestionCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.questions = [];
$scope.data = {
"questions": [
{
"question": "Qw1",
"answers": [
{
"answers": "An1",
"value": 25
},
{
"answers": "An2",
"value": 50
},
{
"answers": "An3",
"value": 75
},
{
"answers": "An4",
"value": 100
}
]
},
{
"question": "Qw2",
"answers": [
{
"answers": "An1",
"value": 25
},
{
"answers": "An2",
"value": 50
},
{
"answers": "An3",
"value": 75
},
{
"answers": "An4",
"value": 100
}
]
}
]
}
$http
.get(JSON.stringify($scope.data))
.then(function(response){
$scope.questions = response.data.questions;
});
}])
I'm using this, and it works great for me
$http.get('url', {params: yourArray}).then(function (result) {
//do sth with data
});
HTTP GET request can't contain data to be sent to the server. You can add a query string to the request. $http option for it is params.
$http({
url: 'example.com',
method: "GET",
params: {...}
});
You dont need to use $http.get() if the data is directly available in controller.
You can use $scope.data instead of $scope.questions. ie in your html file use
{{data.questions[0].question}}
<h2>answer 1</h2>
<p>{{data.questions[0].answers[0].value}}</p>
<p>{{data.questions[0].answers[0].answers}}</p>
I have tried this way and it is working fine:
For example in your controller you have any array like arr variable
var data = Array;
data['Id'] = "1";
data['Name'] ="Test User";
data['UserName'] = "test_user";
data['Email'] = "test#gmail.com";
data['Address'] = "Test Address";
data['Action'] = 'Create';
To pass this array you can use like this
$scope.users = data;
The controller send an array in view page as the variable users
and you can use something like this
ng-repeat="user in users"
Note: this will work for two dimensional array and one dimensional array.
AngularJS has $http service, to get data asynchronously. So it can return any type of data(variable, array, string).
It is better to store data in some common place. Let me show factory pattern which is used for sharing data between controllers.
At first, you should create yourFactory.js file and write the following code:
(function () {
var yourFactory = function () {
var persons = [
{
id: 1,
name: 'Jon',
},
{
id: 2,
name: 'Ben',
},
{
id: 3,
name: 'Joseph',
},
{
id: 4,
name: 'Adam',
}
];
var factory = {};
factory.getPersons = function () {
return persons;
};
return factory;
};
angular.module('personsApp').factory('personsFactory', yourFactory);
}());
and some your controller can use data(just create new .js file for the following controller):
(function()
{
debugger;
var yourController=function($scope, yourFactory) {
/*alert('a1');*/
debugger;
function init() {
debugger;
$scope.yourData=yourFactory.getPersons();
}
init();
};
yourController.$inject=['$scope', 'yourFactory'];
angular.module('yourAppl').controller('yourController', yourController);
}());

Json response via http not working

Currently working on angularjs I am trying to get the data from JSON file and I am showing the result in Ul format. when I searched in SO I found this link I am trying to do the same but still I am not getting
This is what I am trying here in controller
'use strict';
var app = angular.module('myApp', []);
app.controller('MyController', function($scope, $http){
$http.get('sample.json').then(function (response){
$scope.items = response.data.countries;
});
});
HTML Code
<body ng-app="myApp">
<div ng-controller="MyController">
<ul>
<li ng-repeat="(key, value) in items" {{key}}>
</li>
</ul>
</div>
</body>
Here is my plunker kindly help me what i am doing wrong here
One other problem: your JSON is incorrect:
{
"countries": {
"State": [
"TamilNadu"
],
"State": [ <-- Error: duplicate key!
"Karnataka"
]
}
}
Here is an alternative:
{
"countries": [
{ "USA": [
{"State": "California"},
{"State": "Nevada"} ]},
{ "India": [
{"State": "TamilNadu"},
{"State": "Karnataka"} ]}
] }
There are three issues,
(i)You do not need to declare the module twice , once in script.js and other one
in controller.js.
(ii) You were refering to angular 2.0 version ,and coded using angular 1.4 version.
(iii)If you want to show all states from json, it should not have a duplicate key, which you could see from the plunker itself
{ "countries": {
"State": [
"TamilNadu"
],
"State": [ <-- Error: duplicate key!
"Karnataka"
] } }
Here is the working Application

Using AngularJS to consume REST

I've made a REST api using Flask which gives a JSON response on http://localhost:5000/api/person giving the id,names and phone numbers of all the people in a SQLite database. http://localhost:5000/api/person/Name_of_person gives the JSON response corresponding to a person's name. I want to use AngularJS to consume the API so that I can output the names of all the people along with their phone numbers.
index.html
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.id }} + ', ' + {{x.name }} + ',' + {{x.phone}}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:5000/api/person").then(function (response) {
$scope.myData = response.data.objects;
});
});
</script>
</body>
</html>
Contents of http://localhost:5000/api/person
{
"num_results": 5,
"objects": [
{
"id": 24,
"name": "Name2",
"phone": "9999192938"
},
{
"id": 23,
"name": "Name3",
"phone": "9999192938"
},
{
"id": null,
"name": "Name4",
"phone": "9999192938"
},
{
"id": 21,
"name": "Name5",
"phone": "9999192938"
},
{
"id": null,
"name": "Name6",
"phone": "9999192938"
}
],
"page": 1,
"total_pages": 1
}
I am pretty sure my syntax is correct but I am getting no output for index.html. Can anyone please explain where I am going wrong? Is it maybe because it is on a local server and is unable to retrieve the data?
Please test the api by REST client, if the API returns proper result.
If you are having problem in running the application, please test using firefox browser. For chrome you need to serve the index.html through any server as it blocks file:/// protocol and needs http:// to run properly.
Make sure your API supports CORS. You have to set it in API end (see Flask docs) or else you can use CORS plugin for chrome.
If still problem persists there might be any logical/syntactical error. Please paste/share screenshot of your browser console.

Import JSON data for AngularJS Web App

I have been following the Angular tutorials, and I am trying to get my JSON data to appear, yet I know I am doing something wrong, but can't figure out the proper method.
I know that somewhere in my app.js my scope is messed up.
How can I display the Family Name of each product?
Here is the layout I have:
app.js
var eloApp = angular.module('eloMicrosite', []);
eloApp.controller('homeListController', ['$scope', '$http',
function($scope, $http) {
$http.get('/Elo/eloMS.min.json')
.success(function(data) {
$scope.products = data;
});
}]);
eloApp.controller('HomeController', function(){
this.products = $scope.products;
});
HTML
<div ng-controller="HomeController as home">
{{home.products[o]["Family Name"]}}
</div>
JSON Layout
{
"products": [
{
"Family Name": "3201L",
"Type": "IDS",
"Size (inches)": 32,
"Aspect Ratio": "16:9",
"Part Number": "E415988",
"Product Description": "ET3201L-8UWA-0-MT-GY-G",
"Marketing Description": "3201L 32-inch wide LCD Monitor",
"Advance Unit Replacement": "",
"Elo Elite": "",
"Package Quantity": 1,
"Minimum Order Quantity": 1,
"List Price": 1800
},
.
.
.
],
"families": [
{
category: "Category1"
},
{
category: "Category2"
}
],
"accessories": [
{
category: "Category1"
},
{
category: "Category2"
}
]
}
You should add homeListController on your page instead of HomeController, Also need to use this instead of using $scope as you wanted to follow controllerAs syntax, 2nd controller is useless in this scenario, you could remove that from app.js.
Markup
<div ng-controller="homeListController as home">
{{home.products[0]["Family Name"]}}
</div>
Controller
eloApp.controller('homeListController', ['$http',
function($http) {
var home = this;
$http.get('/Elo/eloMS.min.json')
.success(function(data) {
home.products = data.products; //products should mapped here
});
}]);
Demo Plunkr

Extract NodeJS Response into HTML

I want to take this request on NodeJS
Stripe.apiKey = "sk_test_AJKebDsM6QFiK8VpJ06Vq1M1";
stripe.balance.retrieve(function(err, balance) {
// asynchronously called
});
which an example response is
{
"pending": [
{
"amount": 0,
"currency": "usd"
}
],
"available": [
{
"amount": 0,
"currency": "usd"
}
],
"livemode": false,
"object": "balance"
}
and extract the balance information to place it into an HTML label.
How would I go about doing this? Can I pass the response to Angular and then link that to HTML?
You have to have that being served in a route (something like /balance) and then have your angular app consuming it:
If you're using express as your web framework, here's an example (from the top of my head - not tested):
app.get('/balance', function (request, response) {
stripe.balance.retrieve(function(err, balance) {
response.send(balance);
});
});
and here your angular app:
angular.module('myApp', [])
.controller('BalanceController', function ($scope, $http) {
$http.get('/balance').then(function (response) {
$scope.balance = response.data;
});
});

Categories

Resources