0

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];
      };
  }]);
5
  • possible duplicate of Angular - http.get returning undefined Commented Jan 11, 2014 at 0:21
  • Not sure it is the same. Console tells me I have no 'then' method Commented Jan 11, 2014 at 0:44
  • 1
    yeah, wouldn't it be different since his factory is created using $http and mine uses $resource? Commented Jan 11, 2014 at 0:50
  • @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. Commented Jan 11, 2014 at 7:46
  • 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. Commented Jan 11, 2014 at 14:56

1 Answer 1

0
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.