AngularJS How to use RESTful with factory module - javascript

I have been getting an error to make RESTful code for 2 hours.
I have one file has a controller here
angular.module('orderToBeShippedApp',['ng','projectService'])
.controller('orderCtrl',function($scope, Project){
Project.query(function(data){
alert(data);
$scope.projects = data;
});
});
Here is my fatory which is called 'project'.
angular.module('projectService',['ng','ngResource'])
.factory('Project',function($resource){
return $resource('api/url/:projectId.json',{},{
query:{
method:'get',
params: {projectId:"test"},
isArray: false
}
});
});
My html:
<div ng-controller = "orderCtrl" class ="col-sm-8 col-md-9">
<!--Body content -->
<div ng-repeat = "project in projects">
<h2>{{project.name}}</h2>
</div>
</div>
My json is something like
[
{
"age": 0,
"id": "a",
"imageUrl": "a0.jpg",
"name": "b",
"snippet": "Tbaa."
},
{
"age": 1,
"id": "mo",
"imageUrl": "assets/images/phones/mo.0.jpg",
"name": "M\u2122",
"snippet": "The Ned by Android 3.0 (Honeycomb)."
}
]
It doesn't give me any error message on the browser. it seems having a problem on factory function.
Could anyone help me to fix it?

You should change your binding to be name, not ProjectName based on your model definition:
<div ng-controller = "orderCtrl" class ="col-sm-8 col-md-9">
<!--Body content -->
<div ng-repeat = "project in projects">
<h2>{{project.name}}</h2>
</div>
Also, to use ngResource you need to remember to add a script reference to: angular-resource:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-resource.min.js"></script>
UPDATE:
Remove 'ng' Dependency
Pass the resource to the controller as a dependency.
// resource
angular.module('projectService',['ngResource'])
.factory('Project',function($resource){
return $resource('api/url/:projectId.json',{},{
query:{
method:'get',
params: {projectId:"test"},
isArray: false
}
});
});
// controller
angular.module('orderToBeShippedApp',['projectService'])
.controller('orderCtrl',['$scope','Project', function($scope, Project){
Project.query(function(data){
alert(data);
$scope.projects = data;
});
}]);

Your factory may not be giving a console error however it may not be able to bring back the data. Your factory should be looking like this:
angular.module('projectService',['ng','ngResource'])
.factory('Project',function($resource){
return {
projects: $resource('api/url/:projectId.json', {projectId: '#test'})
}
});
}]);
In your controller it should invoke the method like this:
angular.module('orderToBeShippedApp',['ng','projectService'])
.controller('orderCtrl',['$scope','Project',function($scope, Project){
$scope.projects = Project.projects.get({id: 'test'});
}]);
UPDATE:
In order to relax chrome the xmlHttpRequest error you need to run this command from the chrome.exe folder of your machine:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security

Related

How to load JSON array to translate AngularJS webpage with Angular-Translate

I am still learning AngularJS heavily so pardon all my bad quality code/lack of knowledge.
What I want to do
I want to translate my webpage into 2 languages. It currently works when I translate static content using Angular-Translate in the index.html. Like this
function translateConfiguration($translateProvider) {
$translateProvider.useSanitizeValueStrategy(null);
$translateProvider.useStaticFilesLoader({
files: [{
prefix: '../JSON/locale-',
suffix: '.json'
}]
});
$translateProvider.preferredLanguage('en');
$translateProvider.fallbackLanguage('en');
};
I load my simple JSON files for EN and RU locales, structured like this
{
"HEADING" : "Lorem",
"TEXT" : "Ipsum"
}
Then I access the variables through Angular-translate directive
<h1 class="z-logo header-text md-display-1" translate="HEADING">
</h1>
All works as it should.
I want to be able to do the same with my custom directives and ng-repeat.
The issue
I have multiple custom directives in my AngularJS website. For instance
<about-card flex="33" flex-xs="100" flex-sm="100" class="center-content" ng-repeat="data in aboutCardCtrl.info">
</about-card>
Here is the template code that loads through the custom directive and retrieves information from the JSON file
<md-card class="card-bg card-height">
<md-card-title layout="column" class="about-card">
<md-card-title-media class="center-elements">
<img class="md-media-lg" ng-src="{{data.image}}" alt="{{data.imageAlt}}"/>
</md-card-title-media>
<md-card-title-text>
<div class="md-headline card-title-padding">{{data.heading}}</div>
</md-card-title-text>
</md-card-title>
<md-card-content>
{{data.content | translate}}
</md-card-content>
</md-card>
Here is the directive
(function() {
'use strict'
angular
.module('webApp')
.directive('aboutCard', aboutCard);
function aboutCard() {
return {
restrict: 'EA',
priority: 1001,
templateUrl: '../TEMPLATES/about.html',
controller: 'aboutCardController',
controllerAs: 'aboutCardCtrl'
};
};
})();
Here is the controller
(function() {
'use strict'
angular
.module('webApp')
.controller('aboutCardController', aboutCardController);
aboutCardController.$inject = ['JsonData', '$translate'];
function aboutCardController(JsonData, $translate) {
var vm = this;
vm.pathToJson = '../JSON/about-en.json';
vm.info = [];
JsonData.all(vm.pathToJson).then(function(response) {
vm.info = response.data.information;
});
};
})();
Here is the JSON file
{
"information": [{
"heading": "Reliability",
"content": "Our partners have been working on the market for over 10 years",
"image": "../IMG/shield.svg",
"imageAlt": "Reliability Image"
}, {
"heading": "Professionalism",
"content": "We are ready to provide profesional opinion for our clients to ensure the right choice",
"image": "../IMG/people.svg",
"imageAlt": "Professionalism Image"
}, {
"heading": "Development",
"content": "Organization of educational programs in collaboration with our partners",
"image": "../IMG/cogwheel.svg",
"imageAlt": "Development Image"
}]
}
Here I suppose I lack the brainpower to understand how I can load my JSON files and switch between them in the custom directive with ng-repeat. Since The format of the JSON is different.
I've been going through Angular-Translate wiki pages, but all examples feature only index.html and main app.js files and I hardly seem to be able to find/understand examples found in google search like these
https://technpol.wordpress.com/2013/11/02/adding-translation-using-angular-translate-to-an-angularjs-app/
https://github.com/angular-translate/angular-translate/issues/1154
You can use dynamic loader instead of static.
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: 'JSON/{part}/{lang}.json'
});
And then load JSON that you need like this:
$translatePartialLoader.addPart('about');
Language prefix will be automatically add to the path.

Why Angular's $http.get service not working?

I'm having trouble with an example I found on W3Schools about Angular services, on this specific case $http.get one.
I have a json.php file where I have the next JSON:
{
"bands": [
{
"name": "Red hot chilli peppers",
"year": "2009",
},
{
"name": "Maroon 5",
"year": "2005",
},
{
"name": "ACDC",
"year": "2000",
}
]
}
And the Angular and HTML code which should iterate over the object and show the data in it, but it's not working:
JavaScript
var serviceTestApp = angular.module('myapp3', []);
serviceTestApp.controller('controller3', function($scope, $http){
$http.get('json.php').then(function(response){
$scope.myData = response.data.bands;
});
});
HTML
<div ng-app='myapp3' ng-controller='controller3'>
<ul>
<li ng-repeat='x in myData'>
{{x.name}}
</li>
</ul>
</div>
What am I doing wrong here? I use Angular 1.5.0
When you mean not working what exactly do you mean? Do you mean it's successful but doesn't return what you want? In which case you're probably pointing at the wrong thing in the object.
Or does it throw an error?
You should structure it like this:
$http.get('json.php').then(function(response){
// Place a debugger statement here to see if it's successful
$scope.myData = response.data.bands;
}, function(error) {
// No breakpoint needed as you'll see the error in the console window
console.error(error);
});
One other reason could be that you don't have the file in the right place. json.php means that I'd expect it to be in the same folder as the controller.

ng-repeat won't repeat array of data

I am pulling in a JSON file using Angular's $http, but I can't get the formatting right to use ng-repeat for an array of data.
For brevity's sake, here is a sample piece of what I'm working with...
{
name:"Pete",
phone: {
brand: "Nexus",
OS: "Android",
contacts: [
"Alexis",
"Billy",
"Chuck",
"Danny"
]
}
}
Then my ng code is
function($scope, $http) {
$http.get('/my/url')
.success(
function(data){
$scope.contacts = data.phone.contacts;
and my HTML is
<div ng-repeat="names in contacts">
{{names}}
</div>
Only it isn't returning anything. I feel like I am missing a set of [] somewhere?
In JSON:
conAtacts: [
"Alexis",
"Billy",
"Chuck",
"Danny"
]
On view:
<div ng-repeat="names in contacts">
{{names}}
</div>
conAtacts != contacts
Also, you have missed one bracket in JSON.
Should be:
{
name:"Pete",
phone: {
brand: "Nexus",
OS: "Android",
contacts: [
"Alexis",
"Billy",
"Chuck",
"Danny"
]
}
}
Can it be reasons of issue?
Your problem could simply be because you didn't respect the widely recommended practice of the 'point' when you use values that can evolve in AngularJS.
Create an object in the scope :
$scope.dataScope = {}
then in your method
function($scope, $http) {
$http.get('/my/url')
.success(
function(data){
$scope.dataScope.contacts = data.phone.contacts;
and in your html
<div ng-repeat="name in dataScope.contacts">
{{name}}
</div>
Thanks everyone for the as always quick responses. This was a case of sleep deprivation and overthinking things on my part and I left out the ng-controller for the div that the ng-repeat was in.
<div **ng-controller="myCtrl"** ng-repeat="names in contacts">
{{names}}
</div>

AngularJS assign variables to view's scope

I have a somewhat deep JSON object I am trying to using in an HTML template.
{
"service": {
"name": "example",
"url": "abc.com",
"template": "/abc/def/v1",
"metadata": {
"password": "dontguessme",
"username": "supereasy"
}
}
}
I am including a template with the following HTML code.
<div class="modal-body" ng-include="service.instructionsTemplate"> </div>
In the template there is the following.
<h1>Some example content</h1>
{{service.metadata.password}}
My question is instead of referencing the field password via service.metadata, is there a way I can reference it with just the variable password.
I was trying to dig through some of the Angular docs around scoping and templates but came up empty. I saw you can use ng-init.
I was able to use ng-init="metadata = service.metadata" and was able to reference the field password in the template via metadata.password.
However I would just like to reference it by password.
Any ideas?
You already did ng-init="metadata = service.metadata", why not going a step further and do ng-init="password = service.metadata.password"?
Another way would be to bind $scope.password = service.metadata.password inside the controller thayou're using on that page
Edit: OP asked a more general solution
If you don't know the property names, then your best move would be to bind the metadata object, like you already did, and then iterate through its properties using ng-repeat
in your controller:
$scope.metadata = service.metadata
in your template (view):
<h1>Some example content</h1>
<ul>
<li ng-repeat="element in metadata">{{element}}</li>
</ul>
You can easily set the password to something inside the controller:
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.data = {
"service": {
"name": "example",
"url": "abc.com",
"template": "/abc/def/v1",
"metadata": {
"password": "dontguessme",
"username": "supereasy"
}
}
};
$scope.password = $scope.data.service.metadata.password;
});
Here is a demo: http://plnkr.co/edit/KrKeLIP2ANd0rl5NLywF?p=preview

iterate JSON response in Angular project to create new $scope obj i can use in the app

JSON:
[{
"SHFUserID": "400",
"Status": "2",
"Ticker": "DPAX",
"TickerID": "4512",
"TotalBought": "6300.000000",
"TotalSold": "4200.000000",
"TotalSharesNow": "23500.000000"
},
{
"SHFUserID": "400",
"Status": null,
"Ticker": "DPAX",
"TickerID": "4512",
"TotalBought": "70500.000000",
"TotalSold": "47000.000000",
"TotalSharesNow": "45000.000000"
},
{
"SHFUserID": "400",
"Status": null,
"Ticker": "ONP",
"TickerID": "10190",
"TotalBought": "1175.000000",
"TotalSold": "1645.000000",
"TotalSharesNow": "-470.000000"
}]
I am trying to iterate over the Json to create a new obj that only contains unique TickerID BUT still populates the "Pending" or "Settled" value if the record Status is a 1 or 2 respectively.
new desired object {"ticker": "Ticker", "tickerId": "TickerID", "Pending": 0 or 1, "Settled": 0 or 1}
expected result based on example data: {"ticker": "DPAX", "tickerId": 4512, "Pending":0, "Settled": 1},{"ticker": "ONP", "tickerId": 10190, "Pending":0, "Settled": 0}
the javascript code is in a controller.js file in an angular project. No matter what code i use to iterate over the existing JSON I get an empty array returned. I've tried a for loop, for in loop and when I run a simple ticker.length function on the existing JSON it returns 0??
controller.js:
function TickerListCtrl($scope, Ticker) {
var ticker = [];
ticker = Ticker.query();
$scope.tickers = ticker;
$scope.tickerMenu = ticker.length;
...
}
resource.js
angular.module('tickerServices', ['ngResource']).
factory('Ticker', function($resource){
return $resource('http:........../Rest/tickers.php', {}, {
query: {method:'GET', params:{UserID:400}, isArray:true}
});
});
app.js
angular.module('tickercat', ['tickercatFilters', 'tickerServices']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/tickers', {templateUrl: 'partials/tickers-list.html', controller: TickerListCtrl}).
otherwise({redirectTo: '/tickers'});
}]);
tickers-list.html:
...
<div class="span3">
<!--Sidebar content-->
...
<ul class="tickerList">
<li ng-repeat="ticker in tickers | filter:query | orderBy:orderProp">
{{ticker.Ticker}}
<p>{{ticker.Status}}</p>
</li>
</ul>
{{tickerMenu}}
</div>
the browser outputs the "tickerList" as expected but the {{tickerMenu}} returns 0. Not sure what I am missing.
Is it not because you have the controller against the UL element but call the tickerMenu scope attribute after the closing UL?
the answer was to create a custom .filter.
so: ticker in tickers | myCustomFilter
http://docs.angularjs.org/guide/dev_guide.templates.filters

Categories

Resources