Using an array of values in Factory - javascript

Currently I have a factory that is using a json file wrapped in a $http.get request. While not ideal, this works for testing. I'm needing to test the same solution within a SharePoint environment, but json files are not allowed. Ultimately this will be connected to a web api call.
How can I specify the json values within a factory, to allow for testing?
(function() {
var personalViewFactory = function($http) {
var factory = {};
factory.getCustomers = function() {
return $http.get('relationshiptracker.json');
};
return factory;
};
personalViewFactory.$inject = ['$http'];
angular.module('customersApp').factory('customersFactory',
personalViewFactory);
}());
Example of json
[
{
"Segment":"Trading",
"Title":"Narima Ajam ",
"Role":"Oil and Shipping Competency Center Manager ",
"Last Meeting Date":"1/1/2000",
"nextmeetingowner":"",
"CreatedDate":"9/14/2014",
"Modified":"9/14/2014",
"primaryaccountability":"Ajay Buti ",
"otherltEngaged":"Aylin Korkmaz, Carolyn Williams, Karthik Chandrasekar",
"upcomingdate":""
},
{
"Segment":"Upstream",
"Title":"Alison Kenney",
"Role":"IM/IT Manager - The Bridge; (NOLA) - The Bridge",
"Last Meeting Date":"8/5/2014",
"nextmeetingowner":"",
"CreatedDate":"1/2/2000",
"Modified":"2/15/2014",
"primaryaccountability":"Arnold",
"otherltEngaged":"Yero",
"upcomingdate":""
},]

Just place your JSON on a variable in your factory and close over it in your functions.
http://plnkr.co/edit/gWklBTEZWqxPzQjhV19D?p=preview
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#*" data-semver="1.3.0" src="//code.angularjs.org/1.3.0/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="myCtrl">
{{myData}}
<script>
var app=angular.module("app",[]);
app.factory("data",function($http){
var data = [{name:'Bob'},{name:'Amy'}];
return{
getData : function(){
return data;
}
}
});
app.controller("myCtrl",function($scope,data){
$scope.myData = data.getData();
});
angular.bootstrap(document,["app"]);
</script>
</body>
</html>

Related

How to get data from rest api which has basic authentication?

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

REST call in AngularJS does not display record

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.

Use Coldfusion query resultset in AngularJS

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);
}
};
});

html page can not find angular

I have the below code in a html page, running it though I keep getting an error stating that "angular is not defined" I have included angular in the head so i'm not sure why it can't locate it, the url to angular i'm also able to hit directly.
<!DOCTYPE>
<html ng-app="test">
<head>
<title>
<script src="https://code.angularjs.org/1.2.25/angular.js"></script>
</title>
</head>
<body ng-controller="TestController">
<form name="CopyFile" ng-submit="copy(fileId)">
<input type="text" ng-model="fileId"/>
<input type="submit" value="Copy"/>
</form>
<div>{{ message }}</div>
<div>{{ error }}</div>
<script type="text/javascript">
(function () {
var app = angular.module("test", []);
var testController = function ($scope, $http) {
$scope.copy = function (fileId) {
$http.get("http://localhost/test/copy/prod.aspx/ToProd?fileId=" + fileId)
.then(onComplete, onError);
};
var onComplete = function (response) {
$scope.message = response;
};
var onError = function (reason) {
$scope.error = "File could not be copied " + reason;
};
};
app.controller("TestController", ["$scope", "$http"], testController);
} ());
</script>
</body>
</html>
This may not be the cause but you don't want your angular include inside of your title. It should be something more like this:
<!DOCTYPE>
<html ng-app="test">
<head>
<title>My Page</title>
<script src="https://code.angularjs.org/1.2.25/angular.js"></script>
</head>
.....
You gave <script> inside <title>?
<title>
<script src="https://code.angularjs.org/1.2.25/angular.js"></script>
</title>
Please remove it outside.

$http.get succeeds; but can't access output?

How do I get the output from my remote server? - Firebug confirms that the JSON output is correct.
Here is my attempt, I have tried to be as standard as possible (Plnkr):
app.js, controllers.js, factories.js
'use strict';
var nameVersionFactory = angular.module('name.factories.version', []);
nameVersionFactory.factory('Version', ['$q', '$http', function ($q, $http) {
var d = $q.defer();
$http.get('/api').then(function (response) {
d.resolve(response);
});
return d.promise;
}]);
var nameVerCtrl = angular.module('name.controllers.version',
['name.factories.version']);
nameVerCtrl.controller(
'verCtrl', ['$scope', 'Version', function ($scope, Version) {
$scope.version = Version; /* {'status': 'online',
'rest_api_version': '1.1.14',
'server_time': '…'} */
}]
);
var nameApp = angular.module('name', ['name.controllers.version']);
/* CORS */
nameApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
Python REST API (30 lines): https://gist.github.com/anonymous/7d34867aca543911a06f
index.html
<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="name" lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div data-ng-controller="verCtrl">
<pre>{{version | json}}</pre>
<pre>{{version.status}}</pre>
<pre>{{version.data | json}}</pre>
<pre>{{version.data.status}}</pre>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js">
</script>
<script src="scripts/controllers.js"></script>
<script src="scripts/factories.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>
Unfortunately I get no JSON output within those <pre>…</pre> tags.
Promises are no longer unwrapped automatically by scope variables in Angular 1.2+.
So, you have to do:
Version().then(function(result){
$scope.version = result;
});
Moreover, $http returns promises already, so this:
var d = $q.defer();
$http.get('/api').then(function (response) {
d.resolve(response);
});
return d.promise;
Can simply become:
return $http.get("/api");

Categories

Resources