2013-08-14 2 views
15

getTemplates 함수를 반환하지 말아야합니까?AngularJS : 공장에서 다른 함수를 호출하려면 어떻게해야합니까?

예 : 나는 (... 내가 "이/자기/templateFactory"등을 시도)에 "XXXXXXX"을 대체하기 위해 무엇을 잘 모릅니다 :

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

답변

37

templates = this.getTemplates();을함으로써 당신은 객체 속성을 참조하는 아직 인스턴스화되지 않았습니다. 이것에 대해

.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

'템플릿 = obj.getTemplates();'가 비동기로 인해 작동하지 않는 문제가 하나 더 있습니다. 약속을 되 돌리려면 getTemplates를 변경할 수 있습니다. – zsong

6

방법 :

대신 당신은 점차적으로 개체를 채울 수 있습니까?

.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 

    } 
]) 
관련 문제