【发布时间】: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