i´m trying to create a factory with angular.js and y have this json structure from the github api:
[
{
"login": "mojombo",
"id": 1,
"avatar_url": "https://avatars.githubusercontent.com/u/1?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/mojombo",
"html_url": "https://github.com/mojombo",
"followers_url": "https://api.github.com/users/mojombo/followers",
"following_url": "https://api.github.com/users/mojombo/following{/other_user}",
"gists_url": "https://api.github.com/users/mojombo/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mojombo/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mojombo/subscriptions",
"organizations_url": "https://api.github.com/users/mojombo/orgs",
"repos_url": "https://api.github.com/users/mojombo/repos",
"events_url": "https://api.github.com/users/mojombo/events{/privacy}",
"received_events_url": "https://api.github.com/users/mojombo/received_events",
"type": "User",
"site_admin": false
}]
i want to get the data from the url property that contain the info of the user and the idea is get that data from all the user.
this the my code so far from the factory:
angular
.module('app')
.factory('userFactory', function($http){
function getData(){
return $http.get('https://api.github.com/users');
}
function userData(){
getData().success(function(data){
return $http.get('https://api.github.com/users'+ data.url)
}).error()
}
return{
getData : getData
}
});
and this is the controller:
angular
.module('app')
.controller('listUserController', function($scope, userFactory){
$scope.users;
userFactory.getData().success(function(data){
$scope.users = data;
}).error(function(error){
console.log(error);
})
});
but i can get the data, coul you help please.......
Angular encapsulate the api response in an object, try
userFactory.getData().success(function(response){ // response instead of data
$scope.users = response.data; // response.data instead of data
}).error(function(error){
console.log(error);
})
you can try the working plnkr here.
It does:
$resource(user.url)
To request for individual user for its data
result.push(userData)
Push to result and return to controller
userFactory.userData().then(function(data){
vm.userData = data;
});
We're using $resource here because we want to keep the reference to the data in the result array. Then after response come from server, our result array will reflect the changes and show in the view.
Related
I have a JSON object that looks like:
[
{
"empName": "John",
"ID": 1
},
{
"empName": "Sam",
"ID": 2
},
{
"empName": "Ben",
"ID": 3
}
]
In the view I want a dropdown where the user selects one of the names. I'm using ng-options to achieve this:
<select ng-options="item as item.empName for item in employees track by item.ID" ng-model="emp.selected">
</select>
If I hard-code the JSON into the variable employees in my controller the select renders. However if I use:
$.getJSON("path to JSON file",function(json){
$scope.employees = json;
});
The select is not populated. I've tried adding in $scope.$apply() to no avail. Any suggestions?
Update 1
Taking on board the answer from Iso I'm still left with the select not binding. For example If my javascript is:
app.controller('Ctrl', ['$scope', '$http', function($scope, $http) {
$scope.employees = [
{
"empName": "John",
"ID": 1
},
];
$http.get(" --PATH TO JSON-- ").then(function (res) {
$scope.employees = res.data;
console.log($scope.employees);
});
}]);
The select is still only populated with the first name 'John' despite the fact that the console.log returns the full object with all three names.
You need to either call $scope.$evalAsync(), or use $http instead of jQuery here (which I would recommend):
$http.get("path to JSON file").then(function (res) {
$scope.employees = res.data;
});
The reason for this is that $http is aware of AngularJS' digest cycle, whereas jQuery is not.
Refrain from using $scope.$apply() (which can fail if a digest cycle is in progress), and $timeout (which is heavy since it provokes a digest cycle of all your scopes).
Wrap your code inside $timeout:
$.getJSON("path to JSON file", function (json) {
$timeout(function () {
$scope.employees = json;
})
});
The call to $apply may fail when the digest cycle is already in progress.
But consider using the $http instead of using jQuery to pull data.
You should use promises with the $q library in Angular.
var getEmployees = function () {
var deferred = $q.defer();
$.getJSON("path to JSON file", function (json) {
deferred.resolve(json);
});
return deferred.promise;
}
getEmployees().then(res){
$scope.employees = res.data;
}
EDIT
If you use $timeout is not really as correct a solution, as it doesn't give you control over the synchronicity. However, using $http to make your calls comes with promises built in, I believe.
I am facing issue while displaying data in table.
I am using a customservice to fetch data from a json file and then inserting that data into $rootScope of an object.
But when I run the view,it comes blank with no errors.In the view,i am using below line of code in the view to iterate the array of objects "books"
Please guide me.
controller.js
Controllers.controller('BookListCtrl_Student', ['$scope','$rootScope','$http','$location','BookData',
function ($scope, $rootScope, $http, $location, BookData) {
$rootScope.books=[];
$rootScope.books.push(BookData.getData());
$scope.bookLists = ['All Books', 'Available Books'];
$scope.selection = $scope.bookLists[0];
$scope.backToLogin = function() {
$location.path("/main");
}
}
]);
customservice.js
Controllers.factory('BookData',['$http',function(http){
return {
getData: function() {
return http.get('data/books.json').then(function(result){
return result.data;
});
}
};
}
]);
The problem is when you do $rootScope.books.push(BookData.getData()) it calls your getData(), but it never executes the promise. To fix it you would need to handle the promise within the controller and assign the data then.
customservice.js
return http.get('data/books.json');
controller.js
BookData.getData().then(function(resp){
$rootScope.books.push(resp.data);
})
Heres a plunker with a quick example - https://plnkr.co/edit/ivdLd9wilmWW8oUnrMsh?p=preview
I know this question has been answered but given solutions didn't work for me. Everything looks okey, but the contento between curly brackets it's not showing on screen.
<div ng-controller="Hello">
<p>The ID is {{greeting.ip}}</p>
<p>The content is {{greeting.ip}}</p>
</div>
The controller is the folling:
'use strict';
angular.module('sbAdminApp')
.controller('Hello',['$scope','$http', function ($scope, $http) {
$http.get('http://ip.jsontest.com/')
.then(function (data) {
$scope.greeting = data;
console.log($scope.greeting);
});
}]);
And in my app.js, im declaring this:
.state('dashboard.test', {
templateUrl: 'views/test.html',
url: '/test',
controller: 'Hello',
resolve: {
loadMyFiles: function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'sbAdminApp',
files: ['scripts/controllers/helloWorld.js']
})
}
}
})
The JSON URL from where I'm getting the data is this.
And here are the pics with the output from the console:
$scope.greeting = data; This line is wrong.
It should be $scope.greeting = data.data;
EDIT:
Because you are assigning your response from the server to that variable and you need only the data returned from the API call. You response object contains stuff like headers and status code and the data property which actually contains your the data you need like id and stuff. If you want to get the id from your response object you can do it like this: greeting.data.id.
I always name my response variable res or response so not to mess it up. Like this:
$http.get('http://ip.jsontest.com/')
.then(function (res) {
$scope.greeting = res.data;
console.log($scope.greeting);
});
}]);
The problem is you're doing the following:
$scope.greeting = data;
But according to your JSON it should be:
$scope.greeting = data.data;
The data variable holds the whole JSON object, and you want the data key from it.
I have simple RESTful server with Flask and I like to make a simple client with AngularJS using ngResource. The idea is make a GET to the server, and obtain a json file.
This is my services.js
var IpZapServices = angular.module('IpZapServices', ['ngResource']);
IpZapServices.factory('Plug', ['$resource', function($resource) {
return $resource('http://localhost:8003/api/plugs/:id',
{id : "#id"}, {
query: {method: 'GET', params: {}, isArray: false}
});
}]);
And the controllers.js
var IpZapControllers = angular.module('IpZapControllers', []);
IpZapControllers.controller('PlugListCtrl', ['$scope', 'Plug', function($scope, Plug) {
$scope.plugs = Plug.query();
console.log($scope.plugs);
}]);
But, I don't get the json file, get this:
Object { $promise: Object, $resolved: false }
Why? What's I do wrong? Thanks!
EDIT:
This is the raw response that I receipt from the server.
{"plugs": [
{"alarm": [],
"id": 0,
"name": "Plug 0",
"state": false},
.
.
.
{"alarm": [],
"id": 3,
"name": "Plug 3",
"state": false}
]}
EDIT 2: Solution
The problem is in the server. Simply add to the server Flask-CORS and work!
from flask.ext.cors import CORS
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
The solution is from this question
You need to resolve the promise you have created with Plug.query()
Try this:
Plug.query().$promise.then(function (response) {
console.log(response)
$scope.plugs = response;
});
More information on this can be found in the docs on angularjs.org:
https://docs.angularjs.org/api/ngResource/service/$resource
Try this:
var IpZapControllers = angular.module('IpZapControllers', []);
IpZapControllers.controller('PlugListCtrl', ['$scope', 'Plug', function($scope, Plug) {
$scope.plugs = Plug.query();
$scope.plugs.$promise.then(function (result) {
console.log(result);
$scope.plugs = result;
});
}]);
Explanation:
Your call to query will not return the data immediately. It instead returns a promise object that will eventually get your data once the HTTP request is complete (notice that the console message said resolved: false).
Read More:
Promises in AngularJS, Explained as a Cartoon
It seems that you have a promise there.
Don't assign the return value of the function, you need to wait till the promise resolves or rejects
Try
Plug.query().$promise
.then(function (response) {
// success code here
})
.catch(function (err) {})
Whwn connecting to a webapi from the controller, use the success and error promise from the method call.
Ctrl.$inject = ["$scope", "Service"];
function Ctrl($scope, Service) {
Service.getJson().success(function (data) {
$scope.json = data;
})
.error(function (data) {
// data should show the error
});
}
I'm pretty new to Angular JS, but I was making a service to get information from a JSON:
This is the service code:
var staffServices = angular.module('staffServices', ['ngResource']);
staffServices.factory('Staff', function($resource){
return $resource('/api/staff/1', {}, {
query: {method:'GET', params: {}, isArray:false}
});
});
Controller
staffApp.controller('StaffCtrl', function($scope, Staff) {
Staff.query(function(data) {
console.log(data);
$scope.staff = data;
console.log(staff);
});
However, when I run the app, I'm able to see the "data" as an Object but I'm not able to asign it to the scope variable, I get the following "Error: staff is not defined".
Thanks for all your answers !
Instead of
console.log(staff); // this prints the var staff, which is undefined
should be
console.log($scope.staff); // this prints the staff property of $scope