2015-02-12 52 views
0

我CoffeeScript的代碼看起來像這樣

.controller('SignInController', 
    ($scope, CONFIG, restAuth, cookieAuth) -> 
     $scope.signInData = {} 
     $scope.res = {} 
     # TODO: Refactor this to service 

     $scope.processRegistration = -> 
      console.log($scope.signInData) 
      restAuth.post('signin', $scope.signInData) 
      .then(((data) -> 
        if data.res >= 0 
         $scope.res.signInSuccess = true 
         $scope.res.msg = 'You finished login successfully.' 
         cookieAuth.setCookie(data) 
        else 
         $scope.res.signInSuccess = false 
         $scope.res.msg = 'Your login failed. (#{ data.description })' 
       ), 
       (-> 
        $scope.res.signInSuccess = false 
        $scope.res.msg = 'Sorry, it seems that the server is not responding. Please try again later!') 
      ) 


     return 
) 

.controller('SignUpController', 
    ($scope, $http, CONFIG) -> 
     $scope.signUpData = {} 
     $scope.res = {} 
     # TODO: Refactor this to service 

     $scope.processRegistration = -> 
      $http 
      .post('#{ CONFIG.ROOT }/auth/signup', $scope.signUpData) 
      .success (data) -> 
       if data.res >= 0 
        $scope.res.signUpSuccess = true 
        $scope.res.msg = 'You finished registration successfully.' 
       else 
        $scope.res.signUpSuccess = false 
        $scope.res.msg = 'Your registration failed. (#{ data.description })' 
      .error(-> 
       $scope.res.signUpSuccess = false 
       $scope.res.msg = 'Sorry, it seems that the server is not responding. Please try again later!' 
      ) 

     return 
) 

可以看出,上有$scope許多操作,它看起來如何重構這個有一點笨拙..有沒有人有什麼建議?

+2

把它們的服務。如果您在html中使用該函數,則所有範圍函數都可以調用服務函數。 – Gustav 2015-02-12 07:01:49

回答

0

我遵循John Papa風格指南,他推薦controllerAs使用$ scope作爲經典控制器的語法。以下是他陳述的內容:

在$ scope 語法中使用經典控制器上的controllerAs語法。

的controllerAs語法使用其獲取綁定 至$範圍

爲什麼?:controllerAs超過$範圍語法糖這裏面的控制器。您仍然可以將 綁定到View並仍然訪問$ scope方法。

爲什麼?:有助於避免在控制器內使用$ scope方法的誘惑,否則它可能會更好地避免它們或將它們移動到工廠。考慮在工廠使用$ scope,或者在需要時在控制器中使用$ scope。例如,當使用$ emit,$ broadcast或$發佈和訂閱事件時,考慮將 這些用途移到工廠並從控制器調用。

您可以在此找到完整的準則: https://github.com/johnpapa/angularjs-styleguide

相關問題