简体   繁体   中英

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

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;
        });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM