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
Related
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 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.
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);
}
};
});
I am still in study mode of angularjs and just 2 day old. I was trying to make module and so i created seperate js file for it and created module like below.
Also added controller.
var app = angular.module("githubViewer", []);
app.controller("MainCtrl", MainCtrl);
But when i run i get error 'MainCtrl' is not a function, got undefined
here is Plunker
Can someone help me?
After looking in plunker,I think you want to create a separate module in separate file for your controllers and add it to your main module.
For that create module for controllers in separate file,
angular.module("githubViewer", [])
.controller('MainCtrl', function($scope,$http) {
//your logic
});
then add it to your main as dependency in main module
angular.module('plunker', ['githubViewer']);
here is working demo : http://plnkr.co/edit/T9p7Uo2DxUVjqS1wuuiA?p=preview
Ok, you're new to angular, so here's a couple of rules which you must follow until you can prove you need to do otherwise.
You can place definition of module in a separate file. In short plunkers it is often an overkill, but that's what you should be doing in realworld-sized apps. Note that I'm talking about only the module here. Not talking about controllers, factories and other stuff.
Separating body of controller from its inclusion into angular does not bring any benefit. Don't do that.
That said, your files should look like this:
# my_app.module.js
angular.module('myApp', []);
# main.controller.js
var app = angular.module('myApp')
app.controller('MainCtrl', MainCtrl);
function MainCtrl() {
// logic here
}
I check your Plunker.
here is Working Plunker as you want logic of controller in seperate js file and module in seperate file
app.js
function MainCtrl($scope,$http) {
var person = {
firstName: "Kiran",
lastName: "Nandedkar"
};
$scope.name = 'World';
var onUserComplete = function(response){
$scope.user = response.data;
}
var onError = function(reason){
$scope.error = "dfdfdf" ;
}
$http.get("https://api.github.com/users/odetocode")
.then(onUserComplete,onError);
$scope.person = person;
};
module.js
var app = angular.module("githubViewer", []);
app.controller("MainCtrl", MainCtrl);
index.html
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script src="app.js"></script>
<script src="module.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{person.firstName}}!</p>
<div>Login : {{user.login}}</div>
</body>
I have a use case that requires the loading of separate angular applications.
Based on several stack overflow questions and this google thread, it's doable. However, I can't get it to work.
Looking at the documentation:
http://docs.angularjs.org/api/angular.bootstrap
It looks like you need to provide the element (what is the right way to get a handle on the element?), and then how to tie it back to config, controllers, etc. And how would this work with routes? IE how does collision work, ie app a and app b map /foo to /fooa.html and /foob.html respectively... or each app describes its own .otherwise?
Thanks!
So given the requirement that this be a service driven content the only way I can see to do this is kind of a mix between angular and standard html practices. Effectively you'll want to take a page from the plunker book and use Iframes to contain each individual portlet.
<!doctype html> <html lang="en">
<body ng-app="plunker" ng-controller="MainCtrl">
<!-- define foo -->
<div>
<ul class="menu">
<li>foo1</li>
<li>foo2</li>
</ul>
<iframe seamless="true" ng-src="foo.index.html{{fooRoute}}"></iframe> </div>
<div>
<ul class="menu">
<li>bar1</li>
<li>bar2</li>
</ul>
<iframe seamless="true" ng-src="bar.index.html{{barRoute}}"></iframe> </div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script> <script src="app.js"></script> </body> </html>
Then on each of these portlets you'll want to have a completely separate application (including the loading of resources).
<!doctype html>
<html lang="en">
<body ng-app="fooApp">
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script>
var app = angular.module('fooApp', ['fooApp.controllers']);
// Configure the app
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/foo1', {template: '<h1>Foo</h1><h2>foo1</h2>', controller: 'MyCtrl1'});
$routeProvider.when('/foo2', {template: '<h1>Foo</h1><h2>foo2</h2>', controller: 'MyCtrl2'});
}]);
angular.module('fooApp.controllers', []).
controller('MyCtrl1', [function () {
console.log("fooApp.MyCtrl1 invoked.");
}])
.controller('MyCtrl2', [function () {
console.log("fooApp.MyCtrl2 invoked.");
}]);
</script>
</body>
</html>
This is a little less efficient for loading than utilizing a common application base but at the moment this isn't feasible. There is talk at the angular-ui's ui-router team about controlling independent views which may be a workable solution for you but it is currently not implemented, you can follow the discussion at https://github.com/angular-ui/ui-router/issues/84 and chime in with your need. There is also now an issue specifically for this on the ui-router issues list at https://github.com/angular-ui/ui-router/issues/160.
Working plunker of this design: http://plnkr.co/edit/sPoK3I?p=preview
Ok so I figured out how to do this using the angular ui-router the key comes down to the ability of the angular ui-router to transition states without effecting the URL.
The steps to get this working
First instantiate each application as a stand alone application using
a manual bootstrap to an ID'd element.
Attach the ui-router $stateProvider to each application to drive the internal state transitions (routes).
You must leave off the url key here for each defined state or you'll reset the page by changing the url on each state transition.
Setup a state function in a main controller to drive state changes.
The following is the code to get this working:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.0.x" src="http://code.angularjs.org/1.0.7/angular.min.js" data-semver="1.0.7"></script>
<script src="angular-ui-states.min.js"></script>
<script src="app.js"></script>
</head>
<!-- define foo -->
<div id="fooApp" ng-controller="MainCtrl">
<ul class="menu">
<li>foo1</li>
<li>foo2</li>
</ul>
<div ui-view>
</div>
</div>
<script>
// Declare app level module which depends on filters, and services
var app = angular.module('fooApp', ['fooApp.controllers', 'ui.state']);
// Configure the app
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('foo1',
{
template: '<h1>Foo</h1><h2>foo1</h2>',
controller: 'MyCtrl1'
})
.state('foo2',
{
template: '<h1>Foo</h1><h2>foo2</h2>',
controller: 'MyCtrl2'
});
}]);
angular.module('fooApp.controllers', [])
.controller('MainCtrl', ['$scope', '$state', function($scope, $state){
$scope.state = function(name){
console.log('Transition to state ' + name);
$state.transitionTo(name);
}
}])
.controller('MyCtrl1', [function () {
console.log("fooApp.MyCtrl1 invoked.");
}])
.controller('MyCtrl2', [function () {
console.log("fooApp.MyCtrl2 invoked.");
}]);
// manually bootstrap
var div = document.getElementById('fooApp');
console.log(div);
angular.bootstrap(div, ['fooApp']);
</script>
<!-- define bar -->
<div id="barApp" ng-controller="MainCtrl">
<ul class="menu">
<li>bar1</li>
<li>bar2</li>
</ul>
<div ui-view>
</div>
</div>
<script>
// Declare app level module which depends on filters, and services
var app = angular.module('barApp', ['barApp.controllers', 'ui.state']);
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('bar1',
{
template: '<h1>Bar</h1><h2>bar1</h2>',
controller: 'MyCtrl1'
})
.state('bar2',
{
template: '<h1>Bar</h1><h2>bar2</h2>',
controller: 'MyCtrl2'
});
}]);
angular.module('barApp.controllers', [])
.controller('MainCtrl', ['$scope', '$state', function($scope, $state){
$scope.state = function(name){
console.log('Transition to state ' + name);
$state.transitionTo(name);
}
}])
.controller('MyCtrl1', [function () {
console.log("barApp.MyCtrl1 invoked.");
}])
.controller('MyCtrl2', [function () {
console.log("barApp.MyCtrl2 invoked.");
}]);
// manually bootstrap
var div = document.getElementById('barApp');
console.log(div);
angular.bootstrap(div, ['barApp']);
</script>
</body>
</html>
Working plunker of this solution at http://plnkr.co/edit/bXSN8qSMdioZJLYs2zyk?p=preview
Please see my previous answer for a discussion currently occurring to make portlet support more intrinsic in the ui-router.
Figured it out. Here's how to successfully load two angular applications in parallel. Also see that I named the controllers the same for each app to show that dependencies will not collide (since they are scoped within each respective app via module):
<!doctype html>
<html lang="en">
<body>
<script src="lib/angular/angular.js"></script>
<!-- define foo -->
<div id="fooApp">
<ul class="menu">
<li>foo1</li>
<li>foo2</li>
</ul>
<div ng-view>
</div>
</div>
<script>
// Declare app level module which depends on filters, and services
var app = angular.module('fooApp', ['fooApp.controllers']);
// Configure the app
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/foo1', {template: '<h1>Foo</h1><h2>foo1</h2>', controller: 'MyCtrl1'});
$routeProvider.when('/foo2', {template: '<h1>Foo</h1><h2>foo2</h2>', controller: 'MyCtrl2'});
}]);
angular.module('fooApp.controllers', []).
controller('MyCtrl1', [function () {
console.log("fooApp.MyCtrl1 invoked.");
}])
.controller('MyCtrl2', [function () {
console.log("fooApp.MyCtrl2 invoked.");
}]);
// manually bootstrap
var div = document.getElementById('fooApp');
console.log(div);
angular.bootstrap(div, ['fooApp']);
</script>
<!-- define bar -->
<div id="barApp">
<ul class="menu">
<li>bar1</li>
<li>bar2</li>
</ul>
<div ng-view>
</div>
</div>
<script>
// Declare app level module which depends on filters, and services
var app = angular.module('barApp', ['barApp.controllers']);
// Configure the app
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/bar1', {template: '<h1>Bar</h1><h2>bar1</h2>', controller: 'MyCtrl1'});
$routeProvider.when('/bar2', {template: '<h1>Bar</h1><h2>bar2</h2>', controller: 'MyCtrl2'});
}]);
angular.module('barApp.controllers', []).
controller('MyCtrl1', [function () {
console.log("barApp.MyCtrl1 invoked.");
}])
.controller('MyCtrl2', [function () {
console.log("barApp.MyCtrl2 invoked.");
}]);
// manually bootstrap
var div = document.getElementById('barApp');
console.log(div);
angular.bootstrap(div, ['barApp']);
</script>
</body>
</html>
The only remaining question is how to deal with routing collisions.
Well you have 2 choices here:
if you create them as angular.module() there would not be a way atm to connect the modules with each other.
if you create directives with a templateURL to lazyload your components you could broadcast shared attributes and listen to them and you could use the same services in your app.
Probably that would be the best for you.