2013-06-07 3 views
0

Comment utiliser la méthode de fratrie dans une usine?Utilisation des méthodes d'usine dans d'autres méthodes

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

Et Firebug indique l'erreur sur l'initialisation:

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

Je suppose que c'est une erreur conceptuelle, mais ne comprends pas.

Répondre

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

essayer:

... 
    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); 
     } 
    } 
    ... 
+0

> Erreur: self.getData (...) est indéfini – vlad

+0

@vlad la mise à jour. J'ai négligé l'appel à la méthode chaînée. – Yoshi

+0

Merci! Ça marche. – vlad

Questions connexes