【问题标题】:Reuse functions with $scope acces Angular使用 $scope 访问 Angular 重用函数
【发布时间】:2016-12-01 08:52:10
【问题描述】:

我正在解决在两个控制器中重用具有范围访问权限的相同功能的问题 在这里描述: How to include/inject functions which use $scope into a controller in angularjs?

在控制器中:

new CommonService($scope).getSomethingFromDB();

在工厂:

services.factory("CommonService", function (DBService) {

function Factory ($scope) {

    this.$scope = $scope;
}

Factory.prototype.getSomethingFromDB = function () {
    if( angular.isUndefined(this.$scope.vrsteObracuna) || this.$scope.vrsteObracuna === null) {

        this.$scope.loading = true;
        DBService.getSomethingFromDB(
            function success(data) {
                this.$scope.loading = false; //ERROR !!!
                this.$scope.vrsteObracuna = data;
            },
            function error(data, status, headers, config) {
                this.$scope.loading = false;
                etna.notifications.error("Error fetching!");
            }
        )
    }

    return this.$scope.vrsteObracuna;
}

return Factory;
});

问题是从 DBService.getSomethingFromDB 成功回调后 this.$scope.loading 未定义?

【问题讨论】:

    标签: javascript angularjs callback code-reuse


    【解决方案1】:

    你还没有 $scope 进入“成功”闭包,尝试使用这段代码:

    services.factory("CommonService", function (DBService) {
    
    function Factory ($scope) {
    
        this.$scope = $scope;
    }
    
    Factory.prototype.getSomethingFromDB = function () {
        if( angular.isUndefined(this.$scope.vrsteObracuna) || this.$scope.vrsteObracuna === null) {
    
            this.$scope.loading = true;
            var that = this;
            DBService.getSomethingFromDB(
                function success(data) {
                    that.$scope.loading = false; //ERROR !!!
                    that.$scope.vrsteObracuna = data;
                },
                function error(data, status, headers, config) {
                    that.$scope.loading = false;
                    etna.notifications.error("Error fetching!");
                }
            )
        }
    
        return this.$scope.vrsteObracuna;
    }
    
    return Factory;
    });
    

    【讨论】:

    • javascript 中的每个闭包都有自己的“this”对象(范围)。您可以通过变量“that”(或其他变量名)在闭包中使用其他“this”对象(范围)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2017-10-10
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多