Ruby on rails 有角度的风格指南-咖啡脚本?
一位同事在这里找到了一本指南,显然来自谷歌: 综上所述,根据我过去6个月对angular的使用情况,我有一些担忧(我在Rails中使用angular+Coffee,偶尔使用Haml页面):Ruby on rails 有角度的风格指南-咖啡脚本?,ruby-on-rails,angularjs,coffeescript,Ruby On Rails,Angularjs,Coffeescript,一位同事在这里找到了一本指南,显然来自谷歌: 综上所述,根据我过去6个月对angular的使用情况,我有一些担忧(我在Rails中使用angular+Coffee,偶尔使用Haml页面): 文档似乎建议使用类 我有一个PITA处理依赖于JS“this”设置为任何正常值(您可以利用它来调用类方法)的代码。这在回调中尤其痛苦 我的解决方法是将所有方法绑定到$scope,并确保所有控制器代码驻留在1个词法作用域中,例如: MyController = ($scope) -> $scope.
MyController = ($scope) ->
$scope.my_callback= ->
# do something useful, $scope is set to 'the right thing', and don't care about 'this'.
与为控制器创建类的明显建议相反
class MyController
constructor: (@$scope) ->
callback: ->
# @ is in the hands of the caller...
咖啡->JS生产:
var MyController;
MyController = (function() {
function MyController($scope) {
this.$scope = $scope;
}
MyController.prototype.callback = function() {};
return MyController;
})();
请注意,$scope不在“callback”的词法上下文中,它:
a) 意味着你没有挂帽子的钩子
b) coffeescript代码有点混乱。。。如果该方法不是类方法,则作用域将位于上下文中:(
(p.s不打算在这里发动宗教战争,但我可以接受;)将CoffeeScript的类用于Angular controller和服务是一个好主意,因为代码干净且可读性很强。继承是可能的,但我从未测试过。如果以角度方式初始化控制器和服务,则不应出现全局变量问题
此
的问题通常可以使用in-CoffeeScript解决
我的控制器(使用时)如下所示:
嗯。。我曾在控制器中与CoffeeScript类搏斗过一段时间,但同时尝试学习角度指令/作用域/等等会导致灾难。。我并不是真的需要使用它们,所以我放弃了。Desty的配方看起来不错,但我认为我连接的grunt注释器无法处理这种格式 不过,他们在服务方面做得很好
angular.module('app')
.factory 'AccountsService', (UserService, AccountsResource, UtilService, $log) ->
new class
constructor: ->
@account = null
@accounts = []
save: (account) ->
res = new AccountsResource(account)
res.$save()
angular.module('app')
.factory 'AccountsService', (UserService, AccountsResource, UtilService, $log) ->
new class
constructor: ->
@account = null
@accounts = []
save: (account) ->
res = new AccountsResource(account)
res.$save()