AngularJS重构方法到工厂/服务

时间:2014-01-06 17:30:33

标签: angularjs coffeescript refactoring

我最近一直在学习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
]

来自沉重的Rails背景,我的第一个想法是通过将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()。 / p>

如果有人建议重构,阅读或侮辱我如何做这一切都错了 - 我全都听见了。主要目标是将模型相关逻辑移出我的控制器,寻找正确的实现。

1 个答案:

答案 0 :(得分:0)

我知道的两件事在这些版本之间发生了变化。您现在需要单独包含ng-route.js,如果使用内置路由,则主模块依赖于ngRoute。其次,如果您使用的是ng-bind-html,则需要将其更改为ng-bind并对计划在其中显示的字符串使用$ sce.trustAsHtml()。

要更深入地检查更改,请转到此处的更改日志:

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

检查从1.0.6到1.2.7的重大更改部分,以查找升级中可能遇到的任何内容。