简体   繁体   中英

Using factory methods inside other methods

How can I use sibling method inside one factory?

var app = angular.module('sampleApp', []);
app.factory('utils', function($http, $timeout){
    return {
        getData : function(url, func){
            $http.get(url).
                success(func).
                error(function(data, status){
                    alert("WRONG DATA!");
                });
        },
        periodocalUpdate : function(url, period, func, stop){
            if (!stop){
                $timeout(function(){
                    utils.getData(url, func).periodocalUpdate(url, period, func);
                }, period);
            }
        }
    };
});

app.controller('myCtrl', ['$scope', 'utils', function($scope, utils){
    $scope.updateUrl = 'sample.url';
    utils.periodocalUpdate($scope.updateUrl, 2000, function(data){
        console.log(data);
    });
}]);

And firebug shows error on initializing:

Error: utils is not defined .periodocalUpdate/.....

I suppose that is conceptual error, but do not understand where.

    ...
    periodocalUpdate : function(url, period, func, stop){
        if (!stop){
            $timeout(function(){
              //
              //  /- this utils is undefined.
              //  |
                utils.getData(url, func).periodocalUpdate(url, period, func);
            }, period);
        }
    }
    ...

try:

    ...
    getData : function(url, func){
        ...

        return this; // <-- add this
    },
    periodocalUpdate : function(url, period, func, stop){
        var self = this; // <-- and don't forget this
        if (!stop){
            $timeout(function(){
                self.getData(url, func).periodocalUpdate(url, period, func);
            }, period);
        }
    }
    ...

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