Nick S.
Nick S.

Reputation: 418

AngularJS : Factory undefined inside Controller Method

When I call a factory method within the controller it's fine- but when I call a factory method within a controller method it's undefined.

Here's my factory:

app.factory('config', ['$http', '$interval', function($http, $interval, $scope) {
    return {
        lines: function() {
            return $http({
                url: appPath+'/config.php?data=lines',
                method: 'JSON'
            })
        },
        updateLines: function() {
            $http.post(appPath+'/write.php?handler=update line', $scope.lines).
                success(function(data, status, headers, config) {
                    return true;
                }).error(function(data, status, headers, config) {
                    return false;
                });
        }
    }
}]);

My Controller:

app.controller('lineController', function($scope, $interval, $http, config) {
    // this works fine
    config.lines().success(function(data) {
        $scope.lines=data;
    });

    this.addToLine = function(line, customer) {

    };

    this.unassign = function(customer, line) {
        var index = line.indexOf(customer);
        line.splice(index, 1);

        // Cannot read property 'lines' of undefined
        config.updateLines();
    };
});

Inside the controller scope my factory config is defined, however when referencing config in a method the factory is undefined. AngularJs is new to me, so if this is bad practice then I'd appreciate being pointed in the right direction.

Thanks

Upvotes: 1

Views: 762

Answers (1)

Matthew Green
Matthew Green

Reputation: 10401

The error message you are getting appears to be correct. $scope.lines does not exist in your factory but in your controller. So what you might have intended to do would be to pass that value in from the controller to the factory like the below

function in controller

config.updateLines($scope.lines);

function in factory

updateLines: function(lines) {
    $http.post(appPath+'/write.php?handler=update line', lines).
        success(function(data, status, headers, config) {
            return true;
        }).error(function(data, status, headers, config) {
            return false;
        });
}

Upvotes: 3

Related Questions