我第一次尝试将 Coffeescript 与 AngularJS 一起使用。
我想定义一个与服务$http
有依赖关系的新服务
这是我所期待的:
var MyService = function($http) {
this.$http = $http;
};
MyService.prototype.call = function(url, data) {
this.$http(url, data);
};
myApp.service("webService", MyService)
这是注册服务的正常方法,如 AngularJS 文档中所示。
阅读了一篇有关使用 Coffeescript 和 AngularJS 的文章后,我尝试了以下方法:
myApp.service "webService", class
constructor : (@$http) ->
call : (url, data) -> @$http url, data
但是编译的结果给出了这个 javascript:
myApp.service("webService", (function() {
function _Class(_at_$http) {
this.$http = _at_$http;
}
_Class.prototype.call = function(url, data) {
return this.$http(url, data);
};
return _Class;
})());
问题是 Coffeescript 编译器不应将 @$http
替换为 _at_$http
。就我而言,它应该输出以下 javascript:
myApp.service("webService", (function() {
function _Class($http) {
this.$http = $http;
}
_Class.prototype.call = function(url, data) {
return this.$http(url, data);
};
return _Class;
})());
您可以查看online compiler on Coffeescript website给出了预期的结果,所以我不明白为什么我的效果不好。
我需要这个,因为 Angular 注入(inject)引擎无法识别 _at_$http
因为它需要 $http
参数名称。
最佳答案
您需要升级到 CoffeeScript 1.9.1 or higher :
- Internal compiler variable names no longer start with underscores. This makes the generated JavaScript a bit prettier, and also fixes an issue with the completely broken and ungodly way that AngularJS "parses" function arguments.
如果您无法升级,那么您可以手动连接实例变量:
constructor : ($http) -> @$http = $http
CoffeeScript.org 一切正常。因为他们始终运行最新版本。
关于javascript - Coffeescript 编译参数名称错误的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718501/