2014-01-06 61 views
1

最近我一直在刺探學習AngularJS,稍微成功地讓事情按我想要的方式發生,然後我又回到重構我的代碼。我是這樣開始:AngularJS重構方法到工廠/服務

window.App = angular.module('Plant', ['ngResource']) 

App.factory 'Plant', ['$resource', ($resource) -> 
    $resource '/api/plants' 
] 

App.controller 'PlantCtrl', ['$scope', 'Plant', ($scope, Plant) -> 
    $scope.plants = Plant.query() 

    $scope.totalCost = -> 
    # code to sum up the #cost of all the plants 

    $scope.addPlant = -> 
    # code to create a new plant 
] 

從重軌背景的人,我首先想到的是苗條了該控制器由totalCost邏輯移動到Plant工廠。各種擺弄和有關服務和工廠之間的區別無盡的閱讀後,唯一的工作實現我能找到的:

  • 離開工廠單獨
  • 所有我需要
  • 模型相關的方法創建服務
  • 使現有的工廠以服務
  • 使服務提供給控制器

下面的代碼:

App.factory 'Plant', ['$resource', ($resource) -> 
    $resource '/api/plants' 
] 

App.service 'PlantService', ['Plant', (Plant) -> 
    @all = -> 
    Plant.query() 

    @totalCost = (plants) -> 
    # code to sum of #cost 
] 

App.controller 'PlantCtrl', ['$scope', 'PlantService', ($scope, PlantService) -> 
    $scope.plants = PlantService.all() 

    $scope.totalCost = -> 
    PlantService.totalCost($scope.plants) 

    $scope.addPlant = -> 
    # code to create a new plant 
] 

對此並不完全滿意,但我的控制器更薄,而且它已經太長了,所以我準備好解決了。然後我意識到我正在使用1.0.6,當我用最新版本(在編寫本文時爲1.2.7)替換了我的Angular文件後,事情就停止了,我看到了所有非常熟悉的...has no method all()

如果有人建議重構,閱讀或諷刺我如何做這一切都是錯誤的 - 我全部都是耳朵。主要目標是將模型相關的邏輯從我的控制器中移出,以尋找正確的實現。

回答

0

我知道的兩件事是在這些版本之間改變的。您現在需要單獨包含ng-route.js,並且如果您正在使用內置路由,則主要模塊依賴於ngRoute。其次,如果您使用的是ng-bind-html,則需要將其更改爲ng-bind,並在您打算在其中顯示的字符串上使用$ sce.trustAsHtml()。

有關的變化更徹底的檢查去這裏的changelog:

https://github.com/angular/angular.js/blob/master/CHANGELOG.md

檢查重大更改從1.0.6到1.2.7節找到任何你可能會在升級遇到的問題。