2013-08-14 3 views
15

Devo spostare la funzione getTemplates dal ritorno o cosa?AngularJS: Da una fabbrica, come posso chiamare un'altra funzione

Esempio: Non so che cosa per sostituire "XXXXXXX" con (ho provato "questo/auto/templateFactory", ecc ...):

.factory('templateFactory', [ 
    '$http', 
    function($http) { 

     var templates = []; 

     return { 
      getTemplates : function() { 
       $http 
        .get('../api/index.php/path/templates.json') 
        .success (function (data) { 
         templates = data; 
        }); 
       return templates; 
      }, 
      delete : function (id) { 
       $http.delete('../api/index.php/path/templates/' + id + '.json') 
       .success(function() { 
        templates = XXXXXXX.getTemplates(); 
       }); 
      } 
     }; 
    } 
]) 

risposta

37

Facendo templates = this.getTemplates(); si fa riferimento a una proprietà dell'oggetto questo non è ancora istanziato.

Invece si può gradualmente popolare l'oggetto:

.factory('templateFactory', ['$http', function($http) { 
    var templates = []; 
    var obj = {}; 
    obj.getTemplates = function(){ 
     $http.get('../api/index.php/path/templates.json') 
      .success (function (data) { 
       templates = data; 
      }); 
     return templates; 
    } 
    obj.delete = function (id) { 
     $http.delete('../api/index.php/path/templates/' + id + '.json') 
      .success(function() { 
       templates = obj.getTemplates(); 
      }); 
    } 
    return obj;  
}]); 
+0

C'è un altro problema, 'templates = obj.getTemplates();' non funziona a causa dell'async. Puoi cambiare i getTemplates per restituire una promessa e poi ... lo sai :) – zsong

6

ne dici di questo?

.factory('templateFactory', [ 
    '$http', 
    function($http) { 

     var templates = []; 

     var some_object = { 

      getTemplates: function() { 
       $http 
        .get('../api/index.php/path/templates.json') 
        .success(function(data) { 
         templates = data; 
        }); 
       return templates; 
      }, 

      delete: function(id) { 
       $http.delete('../api/index.php/path/templates/' + id + '.json') 
        .success(function() { 
         templates = some_object.getTemplates(); 
        }); 
      } 

     }; 
     return some_object 

    } 
])