user3844782 user3844782 - 1 month ago 14
AngularJS Question

Using Angular $resource, Fetch data on button click not working

I am using angularjs ngresource to fetch a list of data from database on button click. But when i click button nothing happens. What i am doing wrong.

app.js

'use strict';
var App = angular.module('app',['ngResource']);


graph_service.js

'use strict';
App.factory('Graph', ['$resource', function ($resource) {
return $resource(
'http://localhost:8080/SPsystem/stats'
);
}]);


graph_controller.js

'use strict';
App.controller('GraphController', ['$scope', 'Graph', function($scope, Graph) {
var self = this;
self.graph= new Graph();

self.graphs=[];

self.fetchAllstats = function(){
self.graphs = Graph.query();

}
}]);


minimal html

<body ng-app="app" class="ng-cloak">
<div class="generic-container" ng-controller="GraphController as ctrl">
<div class="panel panel-default">
<div>
<input type="button" ng-click="fetchAllstats()" value="Fetch" class="btn btn-success">
</div>

<div class="panel-heading"><span class="lead">List</span></div>
<div class="tablecontainer">
<table class="table table-hover">
<thead>
<tr>
<th>x</th>
<th>y</th>
<th width="20%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="g in ctrl.graphs">
<td>{{g.x}}</td>
<td>{{g.y}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>

Answer

You don't have a method named query in your factory,

Change your factory like this,

App.factory('Graph', ['$resource', function ($resource) {
  {
    // Resource object 
    var resource = $resource('http://localhost:8080/SPsystem/stats');      
      /* Custom function to retrieve a issue list*/
    resource.query= function () {
        return this.query()      
    };       
    return resource;
  })