【问题标题】:AngularJS refactoring methods onto Factories/ServicesAngularJS 将方法重构到工厂/服务上
【发布时间】:2014-01-07 02:03:07
【问题描述】:

我最近一直在努力学习 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()

如果有人建议重构、解读或诬蔑我的做法是错误的 - 我全都听好了。主要目标是将与模型相关的逻辑移出我的控制器,以寻找正确的实现。

【问题讨论】:

    标签: angularjs coffeescript refactoring


    【解决方案1】:

    我知道的两件事在这些版本之间发生了变化。您现在需要单独包含 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 的重大更改部分,以查找升级过程中可能遇到的任何问题。

    【讨论】:

      猜你喜欢
      • 2013-04-20
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2023-04-06
      相关资源
      最近更新 更多