Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm very new to angular, and I'm not understanding why the resource is not working as expected. When I was using the $http.get() request, I could assign it to a variable 'data', and use data.key to get the value. This doesnt seem to work with my current resource setup, I get an error saying "TypeError: Cannot read property '0' of undefined", this wasn't an issue before.

myAppServices.factory('Apprentice',['$resource', function($resource){
  return $resource('javascripts/:apprenticeId/.json', {} ,{
    query: { method:'GET', params : {apprenticeId : 'apprentices'}, isArray:true}
  });
}]);

and the controller....

myAppControllers.controller('apprenticeCtrl',['$scope', 'Apprentice',
    function($scope, Apprentice) {

        var data = Apprentice.query();
        $scope.mainImageUrl = data.images[0];
        var index = data.images.indexOf($scope.mainImageUrl);

        $scope.setImage = function() {
          (index == data.images.length - 1) ? index= 0 : index++;

          $scope.mainImageUrl = data.images[index];
      };
  }]);
share|improve this question
 
possible duplicate of Angular - http.get returning undefined –  Stewie 17 hours ago
 
Not sure it is the same. Console tells me I have no 'then' method –  NoobException 17 hours ago
1  
yeah, wouldn't it be different since his factory is created using $http and mine uses $resource? –  NoobException 17 hours ago
 
@NoobException You're right; this is not a duplicate question. I believe resource accepts a function that is executed when the request is complete like in my answer. –  Words Like Jared 10 hours ago
 
You're right about correct use, the way I had it before, the bindings weren't evaluating, but it bought that might've had something to do with the undefined. With your solution, the bindings from other controllers evaluate, but still no defined array here. –  NoobException 3 hours ago
add comment

1 Answer

myAppControllers.controller('apprenticeCtrl',['$scope', 'Apprentice',
  function($scope, Apprentice) {

    var index;
    var data = Apprentice.query(function () {
      $scope.mainImageUrl = data.images[0];
      index = data.images.indexOf($scope.mainImageUrl);
    });

    $scope.setImage = function() {
      (index == data.images.length - 1) ? index= 0 : index++;

      $scope.mainImageUrl = data.images[index];
    };
}]);

I've never used $resource before but according to the docs you use it like that.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.