Reputation: 541
I try to do reload data button. Heres my json:
[
{
"name": "AAAAAA",
"data": "False"
},
{
"name": "BBBBBB",
"data": "45%"
},
{
"name": "CCCCC",
"data": "12%"
}
]
My javascript:
app.service('service', function($http, $q) {
var deferred = $q.defer();
$http.get('names.json').then(function(data) {
deferred.resolve(data);
});
this.getNames = function() {
return deferred.promise;
}
});
app.controller('FirstCtrl', function($scope, service, $http) {
var vm = this;
vm.reloadData = function() {
console.log("reloading");
vm.loadData();
};
vm.loadData = function() {
var promise = service.getNames();
promise.then(function(data) {
$scope.names = data.data;
console.log($scope.names);
});
}
vm.loadData();
});
My HTML :
<div ng-controller="FirstCtrl as vm">
<table>
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.data}}</td>
</tr>
</tbody>
</table>
<button ng-click="vm.reloadData()">Reload</button>
</div>
My data should reload after click function "vm.reloadData()" but nothing happens, my data dont refresh. Thanks for answers in advance.
Upvotes: 0
Views: 2063
Reputation: 2054
Try this:
Added provision not to kept request data in cache
app.service('service', function($http, $q) {
this.getNames = function() {
return $http.get('names.json', { cache: false});
}
});
app.controller('FirstCtrl', function($scope, service) {
var vm = this;
vm.reloadData = function() {
console.log("reloading");
vm.loadData();
};
vm.loadData = function() {
var promise = service.getNames();
promise.then(function(data) {
$scope.names = data.data;
console.log($scope.names);
});
}
vm.loadData();
});
Upvotes: 1
Reputation: 5262
Change your service
code to something like
this.getNames = function() {
return $http.get('names.json');
}
Upvotes: 0
Reputation: 133453
As per you implementation you are persiting the promise in the service, which is already resolved.
You should define deferred
in the getNames()
service methods.
app.service('service', function ($http, $q) {
this.getNames = function () {
var deferred = $q.defer();
$http.get('names.json').then(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
});
Upvotes: 0