I want to add a sort function to my factory controller in Angular JS.
I have got as far as what I have below:
var albumsApp = angular.module ('albumsApp',[])
albumsApp.factory('albumFactory',function($http) {
return {
getAlbumsAsync: function(callback,$scope){
$http.get('albums.json').success(callback);
},
};
});
albumsApp.controller ('albumController', function ($scope,albumFactory) {
albumFactory.getAlbumsAsync(function(results){
console.log('albumController async returned value');
$scope.albums = results.albums;
});
albumFactory.changeSorting(function(results){
console.log('changeSorting called');
});
});
I get an error "TypeError: albumFactory.changeSorting is not a function" (this refers to the albumFactory.changeSorting) as I have not added it to the factory. I don't know how to do this.
The html code I am using is below: I want to call the function to sort what is in the JSON file alphabetically
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/angular.js"></script>
<script src="js/angular-route.js"></script>
<script type="text/javascript" src="modules/app.js" ></script>
</script>
<title>
</title>
</head>
<body ng-app="albumsApp">
<div data-ng-controller="albumController">
<!-- <ul data-ng-repeat="album in albums| orderBy:'title'"> -->
<ul data-ng-repeat="album in albums">
<li>
Artist is "{{album.artist}}" and title is "{{album.title}}"
</li>
</ul>
<button data-ng-click="changeSorting()">Description</button>
</div>
</body>
</html>
The JSON list is below:
{
"albums":[
{
"artist": "Arctic Monkeys",
"title": "AM"
},
{
"artist": "Nirvana",
"title": "Nevermind"
},
{
"artist": "Buck 65",
"title": "Man Overboard"
}
]
}
Your view is not directly connected to the Angular service—all methods called from the view should be in your controller. You should have a method on your controller and not in your factory. Try moving that function to your controller:
albumsApp.controller ('albumController', function ($scope,albumFactory) {
albumFactory.getAlbumsAsync(function(results){
console.log('albumController async returned value');
$scope.albums = results.albums;
});
$scope.changeSorting = function (){
// your logic goes here
console.log('changeSorting called');
});
});
You can keep your logic in your controller. You can use orderBy in Angular's $filter module to help you sort:
$filter('orderBy')(array, expression, reverse)
Related
ar app = angular.module('chartApp', ['ng-fusioncharts']);
app.controller("MyController2", function($scope, $http){
$http.get('js/data.json').then(function(res,status,xhr){
$scope.countries = res.data;
});
});
I want to use the above JSON as the chart data.
$scope.dataSource = {
"chart": {
"caption": "Column Chart Built in Angular!",
"captionFontSize": "30",
"captionPadding": "25",
........
},
"data": [
]
How can I use the "countries" JSON to be the data for the chart above?
Many examples just declare the JSON inside the "data:[]", is there anywhere to use an external .json file?
Hey we can do something like the following:
angular.module('plunker', ['ng-fusioncharts'])
.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {
const chartProps = {
"caption": "Monthly",
"xaxisname": "Month",
"yaxisname": "Revenue",
"numberprefix": "$",
"theme": "fint"
};
const getDataSource = (data = [], chart = chartProps) => {
return {
chart,
data
}
};
$http.get('./data.json')
.then(({
data
}) => $scope.dataSource = getDataSource(data));
$scope.dataSource = getDataSource();
}]);
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src='https://static.fusioncharts.com/code/latest/fusioncharts.js'></script>
<script src='https://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js'></script>
<script src='https://fusioncharts.github.io/angular-fusioncharts/demos/js/angular-fusioncharts.min.js'></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<fusioncharts id="mychartcontainer" chartid="mychart" width="600" height="400" type="column2d" dataSource="{{dataSource}}"></fusioncharts>
</body>
</html>
Check the plunker link for a live demo.
If you see the app.js, I have a commented part below - which is 'NOT-WORKING' related implementation.
I shall be looking to it in more detail. It seems the issue is $observe is not watching deeply for changes in Object structure. So the stuff works only when we update the reference. So untill then, please follow the above step.
Thanks and lemme know in case of any concern!
I got stuck with the http get method which is used to get the json data.
The http get method is working fine it is actually fetching the json data, but I'm not able to connect it with the object literal.
To explain clearly here is the piece of code where I'm stuck.
var x ={};
$http.get('chart.json') //reading the studentRecord.json file
.success
(function(data1){
//alert(data1);
$scope.x = data1;
});
var conversionChart = new FusionCharts({
type: 'funnel',
renderAt: 'chart-container',
width: "100%",
dataFormat: 'json',
dataSource: x
});
I'm trying to apply the http.get method to the dataSource:to fetch the json data to it but, its not working. And my main task is to apply the http.get request to the dataSource:which makes my code work properly.
And let me give you the entire piece of code to understand better.
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>FusionCharts - Funnel 3D Chart</title>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<script data-require="angular.js#1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.widgets.js"></script>
<script type='text/javascript' src='/js/lib/dummy.js'></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<!-- A funnel 3D Chart showing a conversion analysis in percentage of visiting to purchase in Harry's Supermart website last year
Attribute :
# showPercentValues - set to 1 to show the values in percentage.
-->
<div id="chart-container" ng-controller="ParentCtrl" ng-init='load()' ng-model="dataSource1">FusionCharts will render here</div>
</body>
</html>
script.js
var myApp = angular.module("myApp", []);
//The below code will read the data from student.json file and will pass to the $scope variable
myApp.controller("ParentCtrl", function($scope, $http)
{
$scope.load = function(){
//alert("2");
FusionCharts.ready(function () {
//alert("1");
var conversionChart = new FusionCharts({
type: 'funnel',
renderAt: 'chart-container',
width: "100%",
dataFormat: 'json',
dataSource : function(){
$http.get('chart.json') //reading the studentRecord.json file
.success
(function(data1){
alert(data1);
$scope.dataSource = data1;// binding the data to the $scope variable
});
}
});
conversionChart.render();
});
};
});
chart.json
{
"chart": {
"caption": "Ensource sales report",
"subcaption": "Purchase - Conversion analysis for last year",
"decimals": "1",
"isHollow": "0",
"isSliced": "1",
"labelDistance": "15",
"plotTooltext": "Success : $percentOfPrevValue",
"theme": "fint",
"baseFontSize":"18"
},
"data":
[
{
"label": "Total",
"value": "385634"
},
{
"label": "Contacts",
"value": "175631"
},
{
"label": "Leads",
"value": "84564"
},
{
"label": "Sanctioned",
"value": "35654"
},
{
"label": "Disbursed",
"value": "12342"
}
]
}
My main intention is to use the http.get method to fetch the json data to
dataSource :
Plunker:http://plnkr.co/edit/HUKvROQv8wIiFfx6uZBk?p=preview
I'll be very thankfull if somebody help me with this .Plz help me because I'm new bee to angular
Based on your plunker, the code should be:
var myApp = angular.module("myApp", []);
//The below code will read the data from student.json file and will pass to the $scope variable
myApp.controller("ParentCtrl", function($scope, $http)
{
$scope.load = function(){
//alert("2");
FusionCharts.ready(function () {
//alert("1");
var conversionChart;
$http.get('chart.json') //reading the studentRecord.json file
.success
(function(data1){
//alert(data1);
$scope.dataSource = data1;// binding the data to the $scope variable
conversionChart = new FusionCharts({
type: 'funnel',
renderAt: 'chart-container',
width: "100%",
dataFormat: 'json',
dataSource : $scope.dataSource
});
conversionChart.render();
});
});
};
});
I need to select an element from my data with my $resource, but I have this error :
"Error: $produit1 is not defined GET XHR
http://localhost:8080/Jquery/data/produits.json/1 [HTTP/1.1 404
Introuvable 15ms]
I Think the problem comes from this url: http://localhost:8080/Jquery/data/produits.json/1
because this url http://localhost:8080/Jquery/data/produits.json is OK when i put it on my browser i can see the data, the first dont show me the data (Etat HTTP 404 - /Jquery/data/produits.json/1 )
[
{
"id" : 1,
"reference": "AAA",
},
{
"id" : 2,
"reference": "BBB",
}
]
How can I call my elements by the url please ?
Here is my code :
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Angular ngResource</title>
<script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js"></script>
<script>
var myApp = angular.module('myApp', ['ngResource']);
myApp.factory('Produits',['$resource', function ($resource) {
return $resource('data/produits.json/:id',{id: "#id"},
{
'update': {method: 'PUT'},
'reviews': {method: 'GET'}
}
);
}]);
myApp.controller('produitsCtrl', function($scope, $http,Produits,$log) {
$scope.produits= Produits.query();
$scope.produit1 = Produits.get({'id': 1});
});
</script>
</head>
<body>
<div ng-app="myApp" >
<div ng-controller="produitsCtrl">
Reference 1 : {{ produit1.reference }}
</div>
</div>
</body>
</html>
The thing is that your call :
$resource('data/produits.json/:id',{id: "#id"},
is looking for a json that is generated regarding the id you pass. So your app expects to have a json file that exists only if in your route id=1 exists and returns a json.
$scope.produit1 = Produits.get({'id': 1});
should return a json file with elements as the ones you have currently.
If you want to use the datas contained in your json you need to do this :
var Produits = $resource(data/produits.json);
myApp.controller('produitsCtrl', function($scope, $http,Produits,$log) {
var upd = {
"id": 1,
"reference": "REF"
}
Produits.$update(upd.id);
});
I have try to fetch the json data by using Angular JS. I have successfully fetch through static json data. But now I have try to fetch through external JSON file. Below is my code & there output :
index.html
<!doctype html>
<html ng-app="MyInfo">
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="js/controllers.js" type="text/javascript" ></script>
</head>
<body>
<div ng-controller="MyInfoFunction">
<ul>
<li ng-repeat="item in myinfoVariable">
<div>
<h3> {{item.name }}</h3>
<p> {{item.city}}</p>
<p> {{item.state}}</p>
</div>
</a>
</li>
</div>
</body>
</html>
data.json - js/data.json
[
{
"name" : "myname1",
"city": "mycity1",
"state" : "mystate2"
},
{
"name" : "myname2",
"city": "mycity2",
"state" : "mystate2"
},
{
"name" : "myname3",
"city": "mycity3",
"state" : "mystate3"
}
]
controllers.js : js/controllers.js
var nameSpace = angular.module("MyInfo", []);
nameSpace.controller("MyInfoFunction", function MyInfoFunction($scope, testService) {
function Init() {
$scope.data = {};
testService.getData().then(function(data) {
console.log(data)
});
}
Init();
});
nameSpace.service('testService', function ($http) {
this.getData = function () {
return $http.get('js/data.json');
}
});
Output :
{{item.name }}
{{item.city}}
{{item.state}}
I have try to fetch but unable to get the data. What am I doing wrong please help.
your controller is messy and incorrect, extra } & )
nameSpace.controller("MyInfoFunction", function MyInfoFunction($scope, testService) {
function Init() {
$scope.data = {};
testService.getData().then(function(data) {
$scope.myinfoVariable = data.data;
// console.log(data)
});
}
Init();
});
your .json should be like
[
{"name":"a","city":"b","state":"c"},
{"name":"x","city":"y","state":"z"}
]
if your data.json file is in inside of the js folder then the getting json should be like
this.getData = function () {
return $http.get('js/data.json');
}
You should try to get js/data.json instead of data.json.
nameSpace.service('testService', function ($http) {
this.getData = function () {
return $http.get('js/data.json');
}
});
You need to provide the url relative to your index.html.
If you are hosting your application on http://myapp.com, and the json file you need to get is hosted on http://myapp.com/js/data.json then you can either do $http.get("js/data.json") either $http.get("http://myapp.com/js/data.json").
However, if your json file is hosted on another website, let's say http://mysecondapp.com, then you need to do $http.get("http://mysecondapp.com/data.json")
I have been trying to render the json data to the view by calling
the rest api and the code is as follows:
var Profile = Backbone.Model.extend({
dataType:'jsonp',
defaults: {
intuitId: null,
email: null,
type: null
},
});
var ProfileList = Backbone.Collection.extend({
model: Profile,
url: '/v1/entities/6414256167329108895'
});
var ProfileView = Backbone.View.extend({
el: "#profiles",
template: _.template($('#profileTemplate').html()),
render: function() {
_.each(this.model.models, function(profile) {
var profileTemplate = this.template(this.model.toJSON());
$(this.el).append(tprofileTemplate);
}, this);
return this;
}
});
var profiles = new ProfileList();
var profilesView = new ProfileView({model: profiles});
profiles.fetch();
profilesView.render();
and the html file is as follows:
<!DOCTYPE html>
<html>
<head>
<title>SPA Example</title>
<!--
<link rel="stylesheet" type="text/css" href="src/css/reset.css" />
<link rel="stylesheet" type="text/css" href="src/css/harmony_compiled.css" />
-->
</head>
<body class="harmony">
<header>
<div class="title">SPA Example</div>
</header>
<div id="profiles"></div>
<script id="profileTemplate" type="text/template">
<div class="profile">
<div class="info">
<div class="intuitId">
<%= intuitId %>
</div>
<div class="email">
<%= email %>
</div>
<div class="type">
<%= type %>
</div>
</div>
</div>
</script>
</body>
</html>
This gives me an error and the render function isn't invoking
properly and the render function is called even before the REST
API returns the JSON response.
Could anyone please help me to figure out where I went wrong. Any help is highly appreciated
Thank you
Firstly, you need to pass the model attributes to the template function explicitly. So change the appropriate code in the view to:
var ProfileView = Backbone.View.extend({
el: "#profiles",
//template: _.template($('#profileTemplate').html()), REMOVED
render: function() {
_.each(this.model.models, function(profile) {
var profileTemplate = _.template($('#profileTemplate').html(), {
intuitId: profile.get("intuitId"),
email: profile.get("email"),
type: profile.get("type")
});
$(this.el).append(tprofileTemplate);
}, this);
return this;
}
});
Secondly, your render method is not dependent on the fetch response from being returned from the server. It will get called immediately after the line above it executes and not wait for the fetch response. This behavior you are experiencing is by design. If you want to call render after you get the response back from the server you'll have to use events. You could replace profilesView.render(); with something like:
profilesView.listenTo(profiles, "sync", profilesView.render);
This means that the profilesView will listen for the profiles collection to complete its fetch and fire a sync event. When this occurs, the render function of the view will be called.