javascript - Angular : Factory undefined inside Controller Method

标签 javascript angularjs angularjs-controller angularjs-factory

当我在 Controller 中调用工厂方法时,它很好 - 但当我在 Controller 方法中调用工厂方法时,它是未定义的。

这是我的工厂:

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

我的 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();
    };
});

在 Controller 范围内,我的工厂配置已定义,但是在方法中引用配置时,工厂未定义。 AngularJs 对我来说是新手,所以如果这是不好的做法,那么我会很感激被指出正确的方向。

谢谢

最佳答案

您收到的错误消息似乎是正确的。 $scope.lines 不存在于您的工厂中,而是存在于您的 Controller 中。所以你可能打算做的是将该值从 Controller 传递到工厂,如下所示

Controller 中的函数

config.updateLines($scope.lines);

工厂功能

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

关于javascript - Angular : Factory undefined inside Controller Method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27450636/

相关文章:

javascript - 基于 URL 的重定向 - JavaScript

javascript - 使用单个 json 字符串填充多个选择框

javascript - 类型错误 : Attempted to assign to readonly property

javascript - Controller 总是醒着的吗?

javascript - 第一个函数作为异步函数的柯里函数不起作用

javascript - jQuery while object.hasClass

javascript - 为什么在 AngularJS 中设置服务时,数据没有从一个 Controller 更新到另一个 Controller ?

angularjs - angular-ui-select2 嵌套 ng-repeat 不起作用

javascript - 以 Angular 更新 http 请求回调中的变量

angularjs - 如何测试 Controller 内服务的响应