2015-04-30 98 views
1

我怎麼能在這裏優化的角度重複代碼

angular.module('myApp') 
    .controller('LogsController', function ($scope, LogsService) { 
     $scope.updatingLogs = true; 
     $scope.loggers = {}; 

     LogsService.findAll().$promise.then(function(data) { 
      $scope.loggers = data; 
      $scope.updatingLogs = false; 
     }); 

     $scope.changeLevel = function (name, level) { 
      LogsService.changeLevel({name: name, level: level}, function() { 
       $scope.updatingLogs = true; 
       LogsService.findAll().$promise.then(function(data) { 
        $scope.loggers = data; 
        $scope.updatingLogs = false; 
       }); 
      }); 
     }; 
    }); 

回答

0

優化重複的代碼你可以做創建$scope.findAll方法,這將使的LogsService.findAll()一個Ajax,這樣你可以利用這個功能,而從其他地方多次做。優化版本會。

代碼

angular.module('myApp') 
    .controller('LogsController', function($scope, LogsService) { 
     $scope.updatingLogs = true; 
     $scope.loggers = {}; 

     $scope.findAll = function() { 
      LogsService.findAll().$promise.then(function(data) { 
       $scope.loggers = data; 
       $scope.updatingLogs = false; 
      }); 
     } 

     $scope.changeLevel = function(name, level) { 
      LogsService.changeLevel({ 
       name: name, 
       level: level 
      }, function() { 
       $scope.updatingLogs = true; 
       $scope.findAll(); 
      }); 
     }; 

     $scope.findAll(); //init 
    }); 
+0

這真的很接近我正要說的話。區別在於findAll()不在$ scope中,除非視圖需要直接調用它。 – coblr

+0

@fractalspawn ya..i在$ scope中添加了它,因爲無論哪種方式,我們都可以使用'ng-init'來初始化它,這會使得單元測試更有意義 –

+0

如果它確實幫助了你,它就會變成upvote ..謝謝:) –

1

這裏有一個建議:

angular.module('myApp') 
    .controller('LogsController', function ($scope, LogsService) { 
     $scope.updatingLogs; 
     $scope.loggers = LogsService.findAll(); 

     $scope.changeLevel = function (name, level) { 
      $scope.updatingLogs = LogsService.changeLevel({name: name, level: level}, function() { 
       LogsService.findAll().$promise.then(function(data) { 
        $scope.loggers = data; 
        $scope.updatingLogs = null; 
       }); 
      }); 
     }; 
    }); 
0

取決於你達到什麼。如果你正在尋找代碼清晰度,潛在的重構可能看起來像這樣。

angular.module('myApp') 
    .controller('LogsController', function ($scope, LogsService) { 

    activate(); 

    $scope.changeLevel = function (name, level) { 
     LogsService.changeLevel({name: name, level: level}, changelevelHandler); 
    }; 

    function changeLevelHandler() { 
     $scope.updatingLogs = true; 
     getLogs(); 
    } 

    function getLogs() { 
     LogsService.findAll().$promise.then(function(data) {updateLoggers(data);}); 
    } 

    function updateLoggers(data) { 
     $scope.loggers = data; 
     $scope.updatingLogs = false; 
    } 

    function activate() { 
     $scope.updatingLogs = true; 
     $scope.loggers = {}; 
     getLogs(); 

    } 
});