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.
Related
I have no background in JavaScript and/or Angular but I need to use it for a research project. Shortly, I need to display on a webpage the JSON which is the answer from another component.
Here is the flow:
From the user interface clicking on Submit button a JSON file is sent to another component which does something and returns a JSON. This answer JSON should be displayed on a webpage.
The submit button is as follows and happens in the page named page2.html:
<button name="topage1" class="button-submit" ng-click="generateJSON()">Submit</font></button>
The method generateJSON() has the following code:
$scope.generateJSON = function(){
generateIdForComponents();
addRestrictions();
// REST
data = angular.toJson($scope.schema, true);
headers= {
'Content-Type': 'application/json',
'Cache-Control':'no-cache',
'Access-Control-Allow-Origin': '*'
};
$http.post('http://127.0.0.1:5000/re/z3', data, {headers:headers}).
then(function(response) {
console.log("Merge post ", response.data);
$scope.greeting = response.data;
});
}});
The routing is as follows:
app.config(function($routeProvider) {
$routeProvider
.when("/topage1", {
templateUrl : "page1.html",
controller : "page1Controller"
})
.when("/topage2", {
templateUrl : "page2.html",
controller : "page2Controller"
})
.when("/results", {
templateUrl : "outputOffers.html",
controller : "resultsController"
})
.otherwise({
templateUrl : "page1.html",
controller : "page1Controller"
});
});
What code should I write such that the JSON is displayed on outputOffers.html.
I suggest that in the callback of your $scope.generateJSON method, you redirect to the outputOffers results page (where you want to display the response json data) and you pass the json data as a parameter.
Then in your resultsController you can assign the json data (sent as a parameter) to a $scope.greeting variable to use in your outputOffers view.
You need the routeParams service to pass parameters between views and you will need to inject it into your resultsController.
You will also need the $location service in your page2Controller (in order to perform the redirect) so inject it as follows:
myApp.controller("page2Controller", function($scope, $location){...
Your generateJSON method in your page2 controller would look like this:
$scope.generateJSON = function(){
generateIdForComponents();
addRestrictions();
// REST
data = angular.toJson($scope.schema, true);
headers= {
'Content-Type': 'application/json',
'Cache-Control':'no-cache',
'Access-Control-Allow-Origin': '*'
};
$http.post('http://127.0.0.1:5000/re/z3', data, {headers:headers}).
then(function(response) {
console.log("Merge post ", response.data);
//redirect to the outputOffers view, passing the json data as a parameter
$location.path('results').search({jsonData: response.data });
});
}});
resultsController
Firstly inject the $routeParams to your resultsController as follows so we can get any parameters sent with the url (replace myApp with the name of your app):
myApp.controller("resultsController", function($scope, $routeParams){...
Use an anonymous function in the resultsController which checks whether the jsonData parameter exists (which we sent from the page2 controller). If it does exist then we assign it to a $scope.greeting variable
(function() {
if($routeParams.jsonData == null || $routeParams.jsonData === ""){
//If the jsonData is not set or if it doesnt contain a value (i.e is the empty string) then redirect to the page2 view.
$location.path('topage2');
}else{
//the jsonData parameter does exist so assign it to our scope.greeting variable so we can use it in our view.
$scope.greeting = $routeParams.jsonData;
//log the data to make sure it was passed as parameter:
console.log($scope.greeting);
}
})();
Then in the outputOffers.html view you can use the $scope.greeting variable.
For example if the json contains a "title" and a "message" property then we can do the following:
<p>{{greeting.title}}</p>
<p>{{greeting.message}}</p>
Update:
After seeing a snippet of your json in your comment you could do the following to display it:
<div ng-repeat="g in greeting">
<p>id: {{g.id}}</p>
<p>clockspeed: {{g.offer.clockSpeed}} </p>
</div>
One option can be create a service which will contain two functions to store and to fetch the value. The function that stores the value will be placed in 'page2Controller'.
The function that fetches the value will be placed in resultsController.
Find below a short tutorial.
the service should look like this:
app.config(function($routeProvider) {
$routeProvider
.when("/topage1", {
templateUrl : "page1.html",
controller : "page1Controller"
})
.when("/topage2", {
templateUrl : "page2.html",
controller : "page2Controller"
})
.when("/results", {
templateUrl : "outputOffers.html",
controller : "resultsController"
})
.otherwise({
templateUrl : "page1.html",
controller : "page1Controller"
});
});
app.service('greetingService', function() {
this.greeting = '';
this.store = function (greeting) {
this.greeting = greeting;
}
this.fetch = function () {
return this.greeting;
}
});
page2Controller should look like this:
app.controller('page2Controller', function($scope, greetingService) {
$scope.generateJSON = function(){
generateIdForComponents();
addRestrictions();
// REST
data = angular.toJson($scope.schema, true);
headers= {
'Content-Type': 'application/json',
'Cache-Control':'no-cache',
'Access-Control-Allow-Origin': '*'
};
$http.post('http://127.0.0.1:5000/re/z3', data, {headers:headers}).
then(function(response) {
console.log("Merge post ", response.data);
greetingService.store(response.data);
});
}});
});
resultsController should look like this:
app.controller('resultsController ', function($scope, greetingService) {
$scope.greeting = greetingService.fetch();
});
then, somewhere in your 'outputOffers.html' put this:
{{greeting}}
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´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.
I am very new with AngularJS. Thank you for answer. My code is as follow:
mainModule.controller('MainController', function($scope, $http) {
$http.get('http://localhost/backend/WebService.php', {params: {entity: 'IndexPageEntity'}}).
success(function(data) {
$scope.intro = data[0].IndexPageContent;
});
$http.get('http://localhost/backend/WebService.php', {params: {entity: 'ExhibitionServiceEntity'}}).
success(function(data) {
$scope.exhibit = data[0].ExhibitionServiceContent;
});
$http.get('http://localhost/backend/WebService.php', {params: {entity: 'ShootingServiceEntity'}}).
success(function(data) {
$scope.shooting = data[0].ShootingServiceContent;
});
});
My html file would be:
<div ng-controller="MainController">
<div>{{intro}}</div>
<div>{{exhibit}}</div>
<div>{{shooting}}</div>
</div>
I believe there must be some ways to improve the above code in order to reduce repetition. What I want is to pass entity parameter to the controller on creation.
Using ng-init to pass parameter is discouraged, according to the documentation. Writing custom directive to pass argument to scope does not work since parameters would be overwrittern.
What is the best practice to set params dynamically for use in $http? Thank you.
You should move all the logic to a service and use a directive. I would suggest you to modify your backend to return the same structured data, instead of IndexPageContent, ExhibitionServiceContent, etc. it should be Content or whatever name you want to use. But for now I've added a replace function to get the name of the content from the name of the entity.
mainModule.factory('webService', function($http) {
var apiUrl = 'http://localhost/backend/WebService.php';
function getContent(params) {
var config = {
'params': params
};
return $http.get(apiUrl, config);
};
return {
getContent: function(params) {
return getContent(params)
}
};
});
mainModule.controller('MainController', function($scope, webService) {
var params = {
'entity': $scope.entity
};
var contentName = $scope.entity.replace('Entity', 'Content');
webService.getContent(params).then(function (data) {
$scope.content = data[0][contentName];
});
});
mainModule.directive('EntityContent', function() {
return {
controller: 'MainController',
replace: true,
restrict: 'E',
scope: {
entity: '#entity'
},
template: '<div>{{ content }}</div>'
};
});
<div>
<entity-content entity="IndexPageEntity">
<entity-content entity="ExhibitionServiceEntity">
<entity-content entity="ShootingServiceEntity">
</div>
Create an object data and send the value for the key inside the object at every call.. Also pass the value for key to be set inside the scope..
E.g.
$scope.makeHttpCall = function(data) {
$http.get('http://localhost/backend/WebService.php', {params: data}).
success(function(data) {
$scope[$scope.key] = data[0][$scope.key];
});
};
you can then call this function as
$scope.key = 'IndexPageContent';
data = {
entity : 'yourValueHere'
};
$scope.makeHttpCall(data);
You can set other values as well inside the scope that are dynamic for each request..
I hope this makes sense to you...
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