Gediminas Šukys
Gediminas Šukys

Reputation: 7391

$resource inside in Controller function

I have an issue when putting $resource request inside of Controller function. It works directly from the controller, but doesn't inside the function.

Maybe someone know why? Thanks!

angular.module('Vote', ['ngResource']);
    function VotesController($scope, $resource) {
        $scope.simple = $resource('url'); // works
        $scope.some_item = $scope.simple.get();
        $scope.upvoteQuestion = function($scope, $resource) {
            $scope.simple = $resource('url'); // gets error: undefined
            $scope.some_item = $scope.simple.get();
        }
    }

Upvotes: 0

Views: 238

Answers (1)

maxdec
maxdec

Reputation: 5725

The way you define your function upvoteQuestion means that it takes 2 arguments ($scope and $resource). You need to remove that:

angular.module('Vote', ['ngResource']);
    function VotesController($scope, $resource) {
        $scope.simple = $resource('url'); // works
        $scope.some_item = $scope.simple.get();
        $scope.upvoteQuestion = function() {
            $scope.simple = $resource('url'); // gets error: undefined
            $scope.some_item = $scope.simple.get();
        };
    }

It's a scope problem.
If you define your function with those arguments but don't actually give them when you call the function they'll be set as undefined and that's why you get that error.
If you declare the function without those arguments, as they're not set in the function, it will look for them in the parent scope (the Controller scope) and then find them.

Upvotes: 1

Related Questions