flurp flurp - 6 months ago 11
AngularJS Question

Pass a dynamically created url from my controller to my factory

I can pass variables from my controller to my factory. What I am unable to do is dynamically set the values in a new URL string in my controller and have the factory see this value rather than the original cached one. Mu controller sets the value in

SaveDate.setMyData
like this:

//this function saves the date change
vm.myFunction1 = function ($resource) {

vm.myDate = '/api/Product/SetMilestoneDate/vm.officeKey/vm.whichMilestone/vm.yearSelected/vm.monthSelected/vm.daySelected';

SaveDate.setMyData(vm.myDate);

//this should save the date for milestones
SaveDate.resource.query();
vm.cleanUp();
};


In my factory
setMyData
DOES pull in this new value.(here is the code)

myApp.factory('SaveDate', ['$resource', 'SaveUrl',
function saveDateFactory($resource, SaveUrl) {
var myData = '';

//this grabs the data we need for the url below
function setMyData(data) {
myData = data;
}

return {

setMyData: setMyData,
resource: $resource(myData, {}, {
query: { method: "POST", params: {}, isArray: false }
})
};
}]);


The problem I have is that Angular is pulling the empty string value (the cached value) instead of the new value.

One option would be to call a controller function where I am setting the value in this location:

resource: $resource(myControllerFunction(), {}, {
query: { method: "POST", params: {}, isArray: false }


But I have not been able to call a controller function here without a variety of errors related to scope and undefined. In any other language passing this value is very simple.

If anyone has an idea on how to override the cached value of my current variable or how to call a controller function in this spot, I would appreciate it. Thanks for your help!

Answer

The resource is created on factory injection, and myData original value is used.

If the resource should be created on demand, it has to be wrapped with function.

...
setMyData: setMyData,
resource: () => $resource(myData, {}, {
  query: { method: "POST", params: {}, isArray: false }