Retrieving JSON data from API using AngularJS - javascript

I'm trying to get data from a Web API and display it in a table, but it doesn't work.
I am new to angularjs and i code simple program to get data from the Web API and display in table.but i am not able to get data.
Module
var app = angular.module("myApp", []);
Service
app.service("myService", function ($http) {
//get All Eployee
this.getEmployees = function () {
return $http.get('http://apidemo.gouptechnologies.com/api/admin');
};
})
Controller
app.controller("myCntrl", function ($scope, myService) {
$scope.divEmployee = false;
GetAllEmployee();
function GetAllEmployee() {
alert('home');
var getData = myService.getEmployees();
getData.then(function (emp) {
$scope.employees = emp.data;
}, function () {
alert('Error in getting records');
});
}
});
The JS code is included in the head tag of the HTML file.
HTML body
<body>
<div ng-app="myApp" ng-controller="myCntrl">
<ul>
<li ng-repeat="x in employees">
{{ x.username + ', ' + x.password }}
</li>
</ul>
</div>
</body>
The API URL is legitimate.
Thanks.

Let example a json file in "data/branchList.json" directory, And i am trying to access all data from json file using $http.
It may help you to call a rest service aslo. check this example
data/branchList.json
[
{
"branch_id": 1,
"branch_name": "Mummbai",
"branch_address": "India"
},
{
"branch_id": 2,
"branch_name": "New York",
"branch_address": "US"
}
]
Controller
angular.module('myApp')
.controller('myCntrl', ['$http', '$state', function ($http, $state) {
'use strict';
var vm = this;
function init(){
vm.branchs = '';
loadBranch();
}
init();
function loadBranch(){
$http.get('data/branchList.json').success(function(response){
vm.branchs = response;
})
}
}]);
In this example i am storing all the data in vm.branches variable, you can use this variable in html page
HTML
<li class="col-sm-6" ng-repeat = "branch in vm.branchs">
<strong>{{branch.branch_name}}</strong>
<span>{{branch.branch_address}}</span>
</li>

Related

How to send data from AngularJS controller to its service?

I have my page with element like this
<div ng-app="myApp" class="ng-cloak" ng-controller="MyController as ctrl">
<div class="item" ng-repeat="i in ctrl.items">
<h3>Some text...</h3>
<p ng-bind="i.id"></p>
<button ng-click="alertValue(i.id)">DETAILS</button></p>
</div>
</div>
My controller looks like this and has a method
'use strict';
App.controller('MyController', ['$scope', 'Item', function ($scope, Item) {
$scope.alertValue = function (id) {
alert('clicked:' + id);
}
}
Which works fine, I get the alert with the id. But how do I send this id from controller to my service? I tried following few tutorials, but they are all different and I got completly lost in it. Can anyone explain this to me in a simple way and show how to do this?
May be I need to provide some additional info? Thanks.
I try not to use scope so I would create a function for that click on my controller. Then it's just a matter of doing what you want with it.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
angular.module('my-app', [])
.service('Items', function() {
return {
doWork: function(id) {
console.log(id);
}
};
})
.controller('ItemsCtrl', function(Items) {
var vm = this;
vm.items = [
{ id: 1, name: 'Foo' },
{ id: 2, name: 'Bar' },
{ id: 3, name: 'Baz' },
];
vm.doWork = function(id) {
Items.doWork(id);
};
});
</script>
<div ng-app="my-app">
<div ng-controller="ItemsCtrl as ctrl">
<ul>
<li ng-repeat="item in ctrl.items">
{{item.name}}
<button ng-click="ctrl.doWork(item.id)">Do Work</button>
</li>
</ul>
</div>
</div>
You have to use $http service. $http service facilitates communication with the remote HTTP servers.
$http service use then method in order to attach a callback.
The then() method takes two arguments: a success and an error callback which will be called with a response object.
Using the then() method, attach a callback function to the returned promise.
Something like this:
app.controller('MainCtrl', function ($scope, $http){
$http({
method: 'GET',
url: 'api/url-api'
}).then(function (success){
},function (error){
});
}
See reference here
Shortcut methods are also available.
$http.get('api/url-api').then(successCallback, errorCallback);
function successCallback(response){
//success code
}
function errorCallback(error){
//error code
}
You have to inject the service inside controller to pass some data to it.
app.controller.js
App.controller('MyController', ['$scope', 'ItemService', function ($scope, ItemService) {
$scope.alertValue = function (id) {
ItemService.id = id;
}
}
Please refer this for more information on creating and registering a service in angular.

API, angularJS, to get datas

I never done angularJS from all my life and i am lost.
So i have done this file, to obtain datas from an api with a filter of time.
forecast.js
(function() {
angular.module('application').factory('Forecast', ['$http', '$q', function($http, $q){
var ApiAddr = "api.com/";
forecast.getResults = function(timeStart, timeEnd){
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiAddr, {
params: httpParams,
cache: true
}).then(function(data){
return data;
},
function(response){
console.log(
"HTTP request "+ApiAddr+
" (with parameters tsmin="+httpParams.tsmin+", tsmax="+httpParams.tsmax+
", type="+httpParams.type+", time="+httpParams.time+
(httpParams.motive ? ", motive="+httpParams.motive : "")+
(httpParams.vector ? ", vector="+httpParams.vector : "")+
(httpParams.media ? ", media="+httpParams.media : "")+
") failed with "+response.status
);
return $q.reject(response);
}
);
}];
But i have no idea to make a controller adapter to this. What type of controller i can do ?
Every exemple are based on a fixed json file, with no parameters.
Moreover, i want, in HTML to imput the time filter, but i have totaly no idea of what to do for this. The example i have seen were to get datas, no to send.
Ps : I have made 2 days of research about this, i have never done front end programming in my life.
(function() {
angular.module('application', [])
.factory('Forecast', ['$http', '$q', function($http, $q) {
var apiaddress = 'api.com';
var forecast = {};
forecast.getResults = function(timeStart, timeEnd) {
// We map application varaible names with API param names
var httpParams = {
type: "global",
time: "minute",
tsmin: timeStart,
tsmax: timeEnd
};
return $http.get(apiaddress, {
params: httpParams,
cache: true
}).then(function(result) {
return result.data;
});
};
return forecast;
}])
.controller('SampleCtrl', ['$scope', 'Forecast', function($scope, Forecast) {
$scope.forecastReport = '';
$scope.getForecast = function() {
Forecast.getResults($scope.timeStart, $scope.timeEnd)
.then(function(report) {
$scope.result = report;
}).catch(function(err) {
$scope.result = '';
console.error('Unable to fetch forecast report: ' + err);
});
};
}]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="application" ng-controller="SampleCtrl">
<label>Time Start:
<input type="text" ng-model="timeStart"/></label>
<label>Time End:
<input type="text" ng-model="timeEnd"/></label>
<button ng-click="getForecast()">Get Forecast</button>
<hr/>
<div>
<b>Forecast Result:</b>
</div>
<pre>{{forecastReport | json}}</pre>
</div>
Just inject the factory into your controller like this:
var app = angular.module('application');
app.controller('myController',
['$scope', 'Forecast', function($scope, Forecast) { /* access to Forecast*/}]);
Or with a component (cleaner):
app.component('myComponentCtrl', {
templateUrl: 'template.html'
controller: myComponentCtrl
})
myComponentCtrl.$inject = ['$scope', 'Forecast'];
function myComponentCtrl($scope, Forecast) {/* ... */ }

AngularJS : having multiple functions in a controller

I have a simple controller in AngularJS, and i would like it to have 2 different functions :
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http, $log) {
//1st function
$scope.search = function() {
$http.post('server.php', { "data" : $scope.keywords})
.success(function(data, status) {
$scope.result = data;
})
};
//2nd function
$scope.tableClick = function() {
$log.log('Hello World!');
};
})
I think there's an issue somewhere in the syntax because this script works only when i remove the 2nd function.
When i use the script with the 2 functions (so, what i posted), i get {{ x }} for the following html elements :
<tr ng-repeat="x in result">
<td><a href="wwww.test.com" >{{ x }}</a></td>
Any clues ?
As I said in the comments, there's no echo 'Hello World!' in javascript. If you want to write that phrase on the DOM, then you have to use it as a simple expression. Just like:
$scope.helloWorld = 'Hello World!';
and then in the HTML you simply call it like {{helloWorld}}.
I'm seeing you're testing it with a function. In this case you should return the string 'Hello World!' like
$scope.helloWorld = function () {
return 'Hello World';
};
In the HTML:
{{ helloWorld() }}
In the case you want to simply "log" the Hello World! to the browser's console (which I doubt because you're not paying attention to JS errors): DO NOT USE console.log();. Use AngularJS' built-in service $log instead
A better code
Anyway, if I were you, I'd write that code differently. See
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function ($scope, $http, $log) {
//1st function
$scope.search = function () {
$http.post('server.php', { "data" : $scope.keywords })
.then(function (resp) { //use then instead of success/error
return resp.data;
}, function inCaseOfErrors (err) { //named just for teaching purposes
$log.log(err);
});
};
//2nd function
$scope.tableClick = function () {
$log.log('Hello World!');
};
})
Please make sure that your $scope.result has the right values. Also note that echo doesn't exist in javascript.
In the code below, I took away the server-call and used hard-coded data, just to test:
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http) {
$scope.result = ["apple", "orange", "raisin", "banana"];
//1st function
$scope.search = function() {
//$http.post('server.php', { "data" : $scope.keywords})
//.success(function(data, status) {
//$scope.result = data;
//})
};
//2nd function
$scope.tableClick = function(item) {
console.log("someone clicked the table! Row: " + item);
};
})
Html:
<table>
<tr ng-repeat="item in result">
<td data-ng-click="tableClick(item)">{{ item }}</td>
</tr>
</table>

AngularJs read json file

I have a tree which is created dynamically with json.There is a one controller and in this controller there is a json array.I use this json to create a tree,but i need to read this json from file externally.
My controller;
..........
$scope.myjson =
{
"option1": [
{
"child":[{"label":"Test1" },{"label":"Test2"}],
"id": "option1"
}
],
"option2": [
{
"child":[{"label":"Test1.1",}],
"id": "option2"
}
],
...........
}
Json array reading part(In Controller);
angular.forEach($scope.myjson, function(value, key)
{
if (key === 'option1')
{
for(var t=0;t<$scope.myjson[key][0].child.length;t++)
{
......Somethings.........
}
}
I want to call json file and read it to create a tree.How can i call json file and read in angularjs?
Reading JSON in Angular is pretty straightforward with $http. Keep in mind that $http will return a promise, and you need to resolve it before processing.
Here is a sample code:
$http.get('assets/messages.json').then(function (data) {
/** work with data **/
});
Here you can get a complete tutorial regarding your problem. You just need to modify it in your way.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {$scope.names = response.records;});
});
</script>

use AngularJs NgResource to load JSON file from localhost

Overview
I am building an app (running on MAMP) that holds contact information that will expand to hold more data such as project name & deadline, once this part is functional.
Questions
When the user visits /projects.php#/project/ I would like them to see a list of all the project names with a link to their detail page.
How should I write the following to access all of my data?
Do I need the .json at the end?
What does the #id do?
return $resource('data/project.json/:id', {id: '#id'});
When the user visits /projects.php#/project/a-gran-goodn I would like them to see the details about this project(for now, just the name & address).
How should I write the following to return my data by Id?
$scope.project = $routeParams.id ? Project.get({id: $routeParams.id}): new Project();
plunkr file
http://plnkr.co/edit/7YPBog
project.json
This file lives on http://localhost:8888/angularjs/ProjectsManager/data/project.json
[
{ "address" : [ " 3156 Dusty Highway",
" Teaneck New Jersey 07009-6370 US"
],
"id" : "a-gran-goodn",
"name" : "Grania Goodner",
"phone" : " (862) 531-9163"
},
{ "address" : [ " 62 Red Fawn Moor",
" Rodney Village West Virginia 25911-8091 US"
],
"id" : "b-aime-defranc",
"name" : "Aimery Defranco",
"phone" : " (681) 324-9946"
}
]
app.js
var projectsApp = angular.module('projects', ['ngResource']);
projectsApp.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'ProjectListCtrl',
templateUrl: 'partials/projectlist.html'})
.when('project/:id', {
controller: 'ProjectDetailCtrl',
templateUrl: 'partials/projectdetail.html'
})
.otherwise('/');
});
projectsApp.factory('Project', function($resource) {
return $resource('data/project.json/:id', {id: '#id'});
});
projectsApp.controller('ProjectListCtrl', function(Project, $scope) {
$scope.projects = Project.query();
console.log($scope.projects);
});
projectsApp.controller('ProjectDetailCtrl', function(Project, $routeParams, $scope) {
$scope.project = $routeParams.id
? Project.get({id: $routeParams.id})
: new Project();
});
partials/projectlist.html
Add new item
<ul class="unstyled">
<li ng-repeat="project in projects">
<div class="well">
<h2><small>{{project.id}}</small> {{project.name}}</h2>
View Info for {{project.name}}
</div>
</li>
</ul>
partials/projectdetails.html
<h3>Information</h3>
<p>Name: {{project.name}}</p>
<p>Phone Number: {{project.phone}}</p>
<p ng-repeat="line in project.address">{{line}}</p>
index.php
<?php
header('Access-Control-Allow-Origin: *');
?>
<!doctype html>
<html ng-app="projects">
<head>
<meta charset="utf-8">
<title ng-bind="title" ng-cloak>Restaurant —</title>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
</head>
<body ng-controller="ProjectListCtrl">
<a class="brand" href="#">Projects Manager</a>
<div id="app-container" class="container-fluid">
<div class="row-fluid">
<div class="span12" id="main" ng-view>
</div><!--/.span12-->
</div><!--/.row-fluid-->
<footer>Copyright Projects © 2013</footer>
</div><!--/.container-->
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<!-- Don't forget to load angularjs AND angular-resource.js -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js></script>
<!--Controllers-->
<script src="app.js"></script>
</body>
</html>
Since you can't query against a raw JSON file like you can with RESTful-style URLs (which is what $resource is built to do), you can instead get a copy of the JSON and then build your own query, get, etc. that looks at the data and returns the right thing. It's a bit tricky because you also want to support new Project, which doesn't really make sense when using a file-backed store, but this example supports it:
projectsApp.factory('Project', function($http) {
// Create an internal promise that resolves to the data inside project.json;
// we'll use this promise in our own API to get the data we need.
var json = $http.get('project.json').then(function(response) {
return response.data;
});
// A basic JavaScript constructor to create new projects;
// passed in data gets copied directly to the object.
// (This is not the best design, but works for this demo.)
var Project = function(data) {
if (data) angular.copy(data, this);
};
// The query function returns an promise that resolves to
// an array of Projects, one for each in the JSON.
Project.query = function() {
return json.then(function(data) {
return data.map(function(project) {
return new Project(project);
});
})
};
// The get function returns a promise that resolves to a
// specific project, found by ID. We find it by looping
// over all of them and checking to see if the IDs match.
Project.get = function(id) {
return json.then(function(data) {
var result = null;
angular.forEach(data, function(project) {
if (project.id == id) result = new Project(project);
});
return result;
})
};
// Finally, the factory itself returns the entire
// Project constructor (which has `query` and `get` attached).
return Project;
});
You can use the results of query and get like any other promise:
projectsApp.controller('ProjectListCtrl', function(Project, $scope) {
$scope.projects = Project.query();
});
projectsApp.controller('ProjectDetailCtrl', function(Project, $routeParams, $scope) {
$scope.project = $routeParams.id
? Project.get($routeParams.id)
: new Project();
});
Note the change to Project.get($routeParams.id); also, the updated Plunker also fixes a problem in your $routeProvider configuration.
This is all demonstrated here: http://plnkr.co/edit/mzQhGg?p=preview
i will paste here a generic code i use to fetch json from your local or a remoteserver maybe it will help you:
it uses a factory that you can call when you need it.
app.factory('jsonFactory', function($http) {
var jsonFactory= {
fromServer: function() {
var url = 'http://example.com/json.json';
var promise = $http.jsonp(url).then(function (response) {
return response.data;
});
return promise;
},
hospitals: function() {
var url = 'jsons/hospitals.js';
var promise = $http.get(url).then(function (response) {
return response.data;
});
return promise;
}
};
return jsonFactory;
});
Then when you need to call it:
function cardinalCtrl(jsonFactory, $scope, $filter, $routeParams) {
jsonFactory.hospitals().then(function(d){
$scope.hospitals=d.hospitals;
});
jsonFactory.fromServer().then(function(d){
$scope.fromServer=d.hospitals;
});
}

Categories