How to pass dynamic parameter to angular $ resource
I want to pass a dynamic default parameter value to $ resource. Take a look at Plunker . Here when I passed the default parameter in the factory as
app.factory('myFactory', ["$resource", function($resource) {
return $resource('http://google.com', {timeStamp : (new Date()).getTime()}, {
query : {
method : 'GET',
isArray : true,
cache : false
}
})
}]);
I want the default timeStamp to be dynamic. currently when I click the Refresh button the parameter value is always the same (validation console)
I need this functionality because IE makes cache in GET and I don't want cache data
source to share
This will help you.
app.factory('myFactory', ["$resource", function($resource) {
return $resource('http://google.com', {}, {
query : {
method : 'GET',
isArray : true,
params : { ts : Date.now } // <-- new timestamp will be genrated and assigned to ts
}
})
}]);
every time you call the method myFactory.query()
, a string appears in the url ts
with the current timestamp value.
source to share
var app = angular.module('plunker', ['ngResource']);
app.controller('MainCtrl', function($scope,myFactory) {
$scope.refresh = function(){
myFactory.query({timeStamp : (new Date()).getTime()}).$promise.then(function(){})
}
});
app.factory('myFactory', ["$resource", function($resource) {
return $resource('http://google.com', {}, {
query : {
method : 'GET',
isArray : true,
cache : false
}
})
}]);
No code within a function is executed until the function is called. However, in the object declaration, all of this is done as a constructed object. You can also have this.
app.factory('myFactory', ["$resource", function($resource) {
return $resource('http://google.com', {timestamp: 1433865286924}, {
query : {
method : 'GET',
isArray : true,
cache : false
}
})
}]);
source to share
The correct answer, as Lehnat said,
app.factory('myFactory', ["$resource", function($resource) {
return $resource('http://google.com', {}, {
query : {
method : 'GET',
isArray : true,
params : { ts : Date.now } // <-- new timestamp will be genrated and assigned to ts
}
})
}]);
or if we want to go to the default options section, this can be done as
app.factory('myFactory', ["$resource", function($resource) {
return $resource('http://google.com', { ts : Date.now }, { // <-- new timestamp will be genrated and assigned to ts
query : {
method : 'GET',
isArray : true
}
})
}]);
source to share