Angular js工厂和普通javascript注入工厂使其模块化

时间:2013-12-10 21:18:21

标签: angularjs angularjs-directive angularjs-scope

我创建了一个工厂来使用$ resource调用Rest服务。工厂函数在我的代码中使用了多个位置,并且基于我需要用于不同回调的用法。我想创建一个工厂函数实现的独立实现,我可以在代码的其他部分重用它。

以下是必需的详细信息:

工厂:

app.factory('UnLockFile', function ($resource) {
    return $resource('/api/files/:fileid/checkin',
            {fileid:'@id'},
            {unlock: {method:'PUT', isArray:false}}    
    );

});

其他工厂的工厂重复使用(编辑:现在工作正常)

app.factory('FileImplementation', [ 'UnLockFile',
    function(UnLockFile){       

      var FileImplementation= 
      {

          unLockFile : function (userId, fileId, unlockFileCallback) 
          {
                //Create Unlock object
                var unLockFileObj = new UnLockFile({ userid: userId });

                //make server call to lock the file
                unLockFileObj.$unlock({fileid: fileId }, function(response){
                    //invoke callback
                    unlockFileCallback(response);
                });

          }        
      };

      return FileImplementation; 
    }
  ]);

应用程序代码(这是在Angular范围内;使用指令):

scope.filemodel = FileImplementation;
scope.filemodel.unLockFile(userId, fileId, unlockFileCallback);

请帮忙。

1 个答案:

答案 0 :(得分:0)

根据Charlie的建议,我创建了单独的工厂,实施了单独的工厂操作,然后将这个新工厂注入控制器和指令中以使用它。发布它来关闭这个问题。以下是该工厂的样本。

app.factory('FileImplementation', [ 'UnLockFile', 'LockFile', 'FileEditSession', function(UnLockFile , LockFile, FileEditSession){      

      var FileImplementation= 
      {

          //Unlock file
          unLockFile : function (userId, fileId, unlockFileCallback) 
          {
                //Create Unlock object
                var unLockFileObj = new UnLockFile({ userid: userId });

                //make server call to lock the file
                unLockFileObj.$unlock({fileid: fileId }, function(response){
                    //invoke callback
                    unlockFileCallback(response);
                });

          }


      };

      return FileImplementation; 
    }
  ]);
相关问题