The pattern that I have encountered the most is to create a resource object, then make assignments in the callback. So instead of your current updateSections
function, you would have:
$scope.updateSection = function(index) {
Sections.onUnits.get(
{uuid: $scope.model.sections[index].sectionUUID},
function(results) {$scope.model.sections[index].sectionUnits = results}
)
}
I think that in your code the results of the GET
don't actually get assigned, which is why you're getting back the original array of ids.
Note that the assignment only occurs on successful GET
of the resource. You should have a separate callback to handle any errors.
Also remember that services are singletons, so if you're passing it around, be careful to not change Sections
, or it'll change everywhere else around.
If you wanted to chain requests such that after retrieving a section, you get the materials, then you would do that in your callback, right after the assignment.:
$scope.updateSection = function(index) {
Sections.onUnits.get(
{uuid: $scope.model.sections[index].sectionUUID},
function(results) {
$scope.model.sections[index].sectionUnits = results;
// Should contain some looping mechanism since results is an array.
$scope.getMaterials(results);
}
)
}
A couple of other notes on your code:
- Something seems wrong about your initial method call to get the resource. At that point, you say that the
sectionUnits
object is an array of strings, but yourupdateSection()
method call tries to reference the array as an object. You say that you can get a console printout, so I'm guessing that it works, but you just made a typo - It seems like a bad idea to mutate the sectionUnits object from an array of strings to an array objects. Maybe initialize it as
.sectionUnits = [{unitUUID:'d1'}, {unitUUID:'d2'}]
? - You may want to take a look at Restangular, which basically wraps
$resource
to be a bit more user friendly. I've found it to be really easy to work with.