I'm trying to read json from my Web Service.
I get an error when I try to read teh file form the Web Service.
This is my controller:
var myApp = angular.module('myApp',[]);
myApp.controller('ShowServers', function($scope, $http) {
$http.get('http://localhost/espaidiscos/WebService/ws.php/servidors').
success(function(data, status, headers, config) {
$scope.servers = data;
console.log("work");
}).
error(function(data, status, headers, config) {
// log error
console.log("don't work");
});
});
The html:
<html ng-app='myApp'>
<header>
<script src="./assets/js/angular.min.js"></script>
</header>
<body>
<div ng-controller="ShowServers">
<ul>
<li ng-repeat="server in servers">
{{ server.nom }}
</li>
</ul>
</div>
<!--<div ng-controller="GreetingController">
{{ greeting }}
</div>-->
</body>
<!--<script src="./assets/js/angular.min.js"></script>-->
<script src="./assets/js/controller.js"></script>
<!--<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js"></script>-->
</html>
I can't get any value on the browser. I'm very newbie, any help would be grateful.
Edit:
This is What I get form the Web Service on this URL:
{"servers": [{"idServidors":"1","nom":"file01","ip":"10.0.0.170"},{"idServidors":"2","nom":"dc","ip":"10.0.0.5"}]}
Edit v2:
I tryied with SoapUI and this is what my web service is returning me:
<html>
<head>
<meta content="HTML Tidy for Java (vers. 26 sep 2004), see www.w3.org" name="generator"/>
<title/>
</head>
<body>{"servers": [{"idServidors":"1","nom":"file01","ip":"10.0.0.170"},{"idServidors":"2","nom":"dc","ip":"10.0.0.5"}]}</body>
</html>
Can the problem comes from here? Don't should be a simple json without body tag and other stuff?
EDIT v3:
Now my web service is working fine and returns a truly json response. I don't get any error on the js chrome console.
This is how my html and angular looks now:
<html ng-app='myApp'>
<header>
<script src="./assets/js/angular.min.js"></script>
</header>
<body>
<div ng-controller="ShowServers">
<ul>
<li ng-repeat="server in servers">
{{ server.nom }}
</li>
</ul>
</div>
<!--<div ng-controller="GreetingController">
{{ greeting }}
</div>-->
</body>
<!--<script src="./assets/js/angular.min.js"></script>-->
<script src="./assets/js/controller.js"></script>
<!--<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js"></script>-->
</html>
var myApp = angular.module('myApp',[]);
$http.get('http://localhost/espaidiscos/WebService/ws.php/servidors').success(function(data, status, headers, config) {
$scope.servers = data;
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
}).
error(function(data, status, headers, config) {
// log error
console.log("Error");
});
});
SOLVED:
I copyed the example on w3schools site: http://www.w3schools.com/angular/angular_http.asp
<script>
var MyApp = angular.module('myApp', []);
MyApp.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost/espaidiscos/WebService/ws.php/servidors")
.then(function(response) {
$scope.servers= response.data.servers;
});
});
</script>
It looks like 2 things could be happening. The first is the variable servers isn't instantiated when the ng-repeat runs.
The second is servers doesn't actually have a nom attribute.
$scope.servers = [];
//HTTP Request
Also, print out the servers variable from request to make sure you are getting what you think.
EDIT:
You are making $scope.servers equal to the servers object. You should make it equal data.servers. ng-repeat is only going to work over an array.
EDIT2:
If you're getting an error in the error callback, you must print out the servers response to try and debug it. Without seeing this information I can only guess at what's happening. If you can post the URL in your browser and get JSON fine, but when you try it from javascript, you get an error, then it might have something to do with the response-type. The browser will use a response-type of HTML where from Angular I believe the response-type will be JSON by default. Your server might error out if it doesn't know how to handle the latter.
EDIT3
var myApp = angular.module('myApp',[]);
myApp.controller('ShowServers',function($scope,$http,GetServers){
GetServers.simGetServers($scope);
});
myApp.factory('GetServers', function($http,$timeout){
var simGetServers = function(scope){
$timeout(function(){
data = {"servers": [{"idServidors":"1","nom":"file01","ip":"10.0.0.170"},{"idServidors":"2","nom":"dc","ip":"10.0.0.5"}]}
scope.servers = data.servers;
},200)
};
var getServers = function(scope){
$http.get('http://localhost/espaidiscos/WebService/ws.php/servidors').success(function(data, status, headers, config) {
scope.servers = data.servers;
}).
error(function(data, status, headers, config) {
console.log(data);
});
};
return {
getServers: function(scope){
getServers(scope);
},
simGetServers: function(scope){
simGetServers(scope);
}
}
});
<html>
<header>
<title>StackOverflow Question Response</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</header>
<body ng-app="myApp">
<div ng-controller="ShowServers">
<ul>
<li ng-repeat="server in servers" ng-cloak>
{{ server.nom }}
</li>
</ul>
</div>
<script src="index.js"></script>
</body>
</html>
You put your script outside of the body tag!
The error you show from your web browser's console implies that the server is not providing a JSON object. Check your web service to make sure that it is proving the object the way you expect.
Related
I'm trying to get data from this website through HTTP get method. This website has basic authentication. The data is in JSON format.
This is the rest api website:
(https://shoploapi.herokuapp.com/sellers)
// Code goes here
angular.module('myapp', ['myapp.controller']);
angular.module('myapp.controller', ['myapp.service'])
.controller('testController', function($scope, testService) {
$scope.posts = {};
function GetAllPosts() {
var getPostsData = testService.getPosts();
getPostsData.then(function(post) {
$scope.posts = post.data;
}, function() {
alert('Error in getting post records');
});
}
GetAllPosts();
});
angular.module('myapp.service', [])
.service('testService', function($http) {
//get All NewsLetter
this.getPosts = function() {
return $http.get('https://shoploapi.herokuapp.com/sellers');
};
});
angular.module('myApp', ['base64'])
.config(function($httpProvider, $base64) {
var auth = $base64.encode("bhupendra7:ice123age456");
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + auth;
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-base64/2.0.5/angular-base64.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-app="myapp">
<h1>Hello Plunker!</h1>
<div ng-controller="testController">
<div>
<ul>
<li ng-repeat="post in posts">
{{post.careof}} {{post.district}} {{post.gender}} {{post.name}}
</li>
</ul>
</div>
</div>
</body>
</html>
Here's the link to my Plunker:
(https://plnkr.co/edit/7pqljm?p=preview)
Can anyone help?
There are 2 problems in your code.
1. You have a typo
In angular.module('myApp', ['base64']), change to module name to myapp
2. The way you have injected your myapp.controller to myapp module
Change it to angular.module('myapp', []); You will also need to reorder your code. Check out the Plunker I have created for you.
Even if you fix the above two problems, you will still face a CORS problem from Heroku. Depending on your server-side technology (NodeJS, Rails etc.), you will need to enable it from the server to be able to communicate with your app. You can also look in to JSONP with AngularJS
Hope this helps
I made the below code to learn Angular. It uses the input entered by user to make an ajax request for a json file that contains a list of object, then print that list to the user.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript">
angular.module('myApp', [])
.controller('myController', function($http) {
var ctlr = this;
ctlr.param = "";
ctlr.responses = [];
this.makeQuery = function() {
$http.get('http://localhost:8080?p=' + ctlr.param))
.then(function(data) {
ctlr.response = data; // data -> [{key1: value1,...},...]
});
};
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="myController as mc">
<input type="text" ng-model="mc.param">
<input type="submit" ng-click="mc.makeQuery()" value="Submit">
<ul>
<li ng-repeat="res in responses">
<span>{{res.key1}}, {{res.key2}}</span>
</li>
</ul>
</div>
</body>
</html>
When I run this code in Chrome, I see a list of empty bullet points. Chrome DevTools shows the json file returned as expected so I know ctlr.param works. However the list has empty bullet points so ng-repeat does not work correctly. It seems I cannot access cltr.responses properly. Does anyone know why?
Your responses object is binded to this and not to $scope as you are using controller as
You should use mc.responses instead of responses
<li ng-repeat="res in mc.responses">
<span>{{res.key1}}, {{res.key2}}</span>
</li>
You can read more from johnpapa style
Above solution is right but as i checked the complete code and found that there is one mistake.
In script code
ctlr.response = data; // data -> [{key1: value1,...},...] should be
ctlr.responses = data; // data -> [{key1: value1,...},...]
I need to get the data from a json file below(please click the "Json File" link to see how is that structure of Json file) but i am confused what should I put after "$Scope.listOfRecipe=", I put response.data.recipes, but it doesn't work here and there are some error .
angular.js:12520 TypeError: Cannot read property 'recipes' of undefined
at recipesController.js:10
at angular.js:10296
at angular.js:14792
at r.$eval (angular.js:16052)
at r.$digest (angular.js:15870)
at r.$apply (angular.js:16160)
at g (angular.js:10589)
at T (angular.js:10787)
at XMLHttpRequest.w.onload (angular.js:10728)
Json File here is my json file
This is my recipesControllers.js
var myApp = angular.module('myApp', []);
myApp.controller('namesCtrl',function ($scope, $http) {
$scope.listOfRecipe = null;
$http.get('http://164.132.196.117/chop_dev/recipe/recipes.json')
.success(function (response) {
$scope.listOfRecipe = response.data.recipes;
})
});
This is my Index.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="namesCtrl">
<ul>
<li ng-repeat="x in listOfRecipe ">
{{ x.Recipe.id + ', ' + x.Recipe.name }}
</li>
</ul>
</div>
<script src="C:/Users/Enetfirm Server/Desktop/AngularJs/recipesController.js"></script>
</body>
</html>
You can console.log(response) and see what the response is and adjust your code accordingly.
But I would recommend using the standard promise pattern:
$http.get('http://164.132.196.117/chop_dev/recipe/recipes.json')
.then(function(resp) {
$scope.listOfRecipe = resp.data.recipes;
})
.catch(function(errResp) {
// catch error
})
.finally(function() {
// when it is done do something in the view
// remove a spinner gif or scroll to top ...
});
Can you verify the file is downloading on the developer tools - network tab ?
Make sure it's working, and please console.log response and response.data in order to verify its there !
It's a Json file means the response is the Json it self and not res.data
Please check it and reply for sharing your solution
This is my first AngularJS project. I followed this website to create a simple html to display a single record by calling restful services. The rest works with the url "http://localhost:8080/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009".
Here is my html:
<html ng-app="cgApp" ng-controller="CgseqCtrl">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
<script src="../js/controller.js"></script>
</head>
<body>
<div>
<hr>
<h2>{{seq.analysisId}}</h2>
<h2>{{seq.library}}</h2>
</hr>
</div>
</body>
</html>
I defined the resource in a service js
//service.js
angular.module('cgApp', ['ngResource'])
.factory('CgseqService', function ($resource) {
return $resource('http://localhost:8080/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009',
{get: {method: 'GET'}
});
});
The controller:
//controller.js
angular.module('cgApp', ['ngResource'])
.controller('CgseqCtrl', ['CgseqService', '$scope', function (CgseqService, $scope)
{
$scope.getSeq = function(response) {
CgseqService.get(function(data) {
$scope.seq = data;
});
};
}]);
When I started my http server with Node.js and typed the url in the browser, nothing is displayed. What did I do wrong?
Several errors.
You didn't load your factory code. It looks like you only loaded your controller.js (I'm assuming your factory code is in a different file since in your example you commented it as //service.js):
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
<script src="../js/controller.js"></script>
</head>
np-controller should say ng-controller:
<html ng-app="cgApp" np-controller="CgseqCtrl">
You also never called your $scope.getSeq function:
$scope.getSeq = function(response) {
CgseqService.get(function(data) {
$scope.seq = data;
});
};
You should call $scope.getSeq() somewhere to actually invoke it.
I'm trying to use AngularJS in my cfm files to display data from cfquery resultset.
I used below code in my cfm file.I'm not able to see any output.
P.S. I'm really new to AngularJS. So if anyone can please help me out here it would be great.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html ng-app="Demo">
<head>
<link rel="stylesheet" href="/Applications/_Common/style.css" type="text/css">
</head>
<body>
<cfsetting enablecfoutputonly="Yes">
<CF_GetProjectData project_number=349246 query_name="GetProject">
<div ng-controller="DemoController">
<div ng-repeat="number in project">
{{number.project_number}} - {{number.project_name}}
</div>
<!-- <input name="imprint" type="text" size="10" ng-model="first">
<p>{{first}}</p> -->
</div>
<cfoutput>
<script language="JavaScript" src="/CFIDE/scripts/wddx.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script language="text/javascript">
var theProjectArray; < cfwddx action = "CFML2JS"
input = "#GetProject#"
toplevelvariable = "theProjectArray" >
</script>
<script>
var Demo = angular.module("Demo", []);
Demo.controller("DemoController", function($scope) {
$scope.project = theProjectArray;
alert(theProjectArray);
});
</script>
</cfoutput>
<cfsetting enablecfoutputonly="No">
</body>
</html>
I am not sure about Angular.js but based on the code you have posted, it seems, you need to wrap ng-controller div in cfoutput. This is because you have set enablecfoutputonly="Yes". So only the content inside cfoutput will be rendered.
I'm a CF developer that's currently learning Angular as well. First of all Angular is a MVC framework and will work for you best of you follow the rules of Separation of Concern (SoC). I know unless you are using Object Relational Mapping (ORM) in CF this is counter intuitive but it will save you so much hassle and trouble shooting later.
For your problem right now though i would
combine both script blocks.
your variable theProjectArray is defined with var so it's not
global. Are you sure it's making it into your controller?
the line toplevelvariable = "theProjectArray" > ... is the greater
than sign a type-o?
After you've done those i would console.log(theProjectArray); right after it's defined. Then console.log(theProjectArray); again in your controller to ensure it's getting passed in properly.
Just for your reference here is a very basic example of a controller and a factory in angular calling a CFC. Since i've been doing things this way the only time i use ColdFusion is to retrieve data and model it. It's simplified my code and logic quite a bit and has allowed me to do a lot more now that i'm not leaning on ColdFusion.
var myapp = angular.module("test.myapp", [])
myapp.controller("MyController", function($scope, getevent) {
$scope.myData = {};
$scope.myData.doUpdate = function(item, event) {
getevent.GetProgram(item).success(function(data, status, headers, config) {
console.log(data.DATA);
$scope.test = data.DATA;
$scope.test.DATE = new Date(data.DATA.DATESTART);
});
getevent.GetProgram(item).error(function(data, status, headers, config) {
console.log("FAILED: "+item);
alert("AJAX failed!");
});
}
});
myapp.factory('getevent', function($http){
return {
GetProgram: function(item) {
var programInfo = '/foundation/cfc/calendar.cfc?method=getevent&eventid='+item;
return $http.get(programInfo);
}
};
});