簡體   English   中英

$ scope重用函數訪問Angular

[英]Reuse functions with $scope acces Angular

我對在這里描述的兩個控制器中通過范圍訪問重用相同功能的問題提出了疑問如何在angularjs的控制器中包含/注入使用$ scope的函數?

在控制器中:

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是未定義的?

您還沒有$ 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;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM