AngularJs将公共代码重构为服务

时间:2015-10-30 08:07:48

标签: javascript angularjs refactoring

在angularJs中,我有两个控制器,它们有一个共同的功能。我编写一个服务并将这个常用方法投入使用。

以下哪一种方法是正确的,或者有更好的方法可以做到这一点。

  1. 通过发送经过修改的$scope个对象来调用公共服务
  2.   angular.module('app').controller('ACtrl', function($scope, $rootScope, MyCommonService) {
                $scope.firstObj = {....};
                //can required more than 4 param
                MyCommonService.doCommontask(firstObj........);
            });
    
            angular.module('app').service('MyCommonService', function(RestService) 
            {
                this.doCommontask = function (firstObje.......) {
                    //following call is to service which do rest call and 
                    //almost all work is inside the call back.
                    RestService.xxxGET().$promise.then(function(data)
                    {
                      // firstObje gets and others modified here and need
    
                      //value to be reflected in view controlled by ACtrl
    
                      // most of params of docommonTask used here
                    });
    
                };
            });
    
    1. 调用常用服务并使用$rootScopecontroller访问被修改的obj
    2. angular.module('app').controller('ACtrl', function($scope, $rootScope, MyCommonService) {
                  //though $rootScope, will only used by this controller and,commonService
      
                  $rootScope.firstObj = {....}; 
                  //no param as rootScope is used 
                  MyCommonService.doCommontask();
              });
      
          angular.module('app').service('MyCommonService', function($rootScope, RestService) {
              this.doCommontask = function () {
                  //following call is to service which do rest call and 
                  //almost all work is inside the call back.
                  RestService.xxxGET($rootScope.firstObj...).$promise.then(function(data){
                    // firstObje gets and others modified here and need
                       value to be reflected in view controlled by ACtrl
                    // most of params of docommonTask used here
                  });
      
              };
          });
      

      要遵循哪一个或者有更好的方法/重构代码哪个有充分的理由?

      请建议重构的最佳做法。

0 个答案:

没有答案