AngularJS服务中的问题返回函数
Issue returning function in AngularJS Service
这是我的服务:
web.factory('distance', function() {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
};
return function(origin, destination) {
var R = 6371; // Radius of the earth in km
var dLat = (origin.lat()-destination.lat()).toRad(); // Javascript functions in radians
var dLon = (origin.lng()-destination.lng()).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(origin.lat().toRad()) * Math.cos(destination.lat().toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c; // Distance in km
};
});
在我的远程服务中返回函数是爆炸。显然,它无法看到名为origin.lat()的方法。我认为在javascript中你不需要初始化任何东西作为一个类型事先?
这是错误我得到在铬在"origin.lat()":
第一次出现
Uncaught TypeError: undefined is not a function
感谢任何帮助。由于
这里的错误是lat没有被标识为'origin'上的函数。
现在你的工厂应该返回一个包含函数而不是函数的对象。
在将函数注入到你想要的地方之后,你将执行对该函数的调用。
web.factory('distance', function() {
// Should this be here???
Number.prototype.toRad = function() {
return this * Math.PI / 180;
};
return
{
calculate:function(origin, destination) {
var R = 6371; // Radius of the earth in km
var dLat = (origin.lat()-destination.lat()).toRad(); // Javascript functions in radians
var dLon = (origin.lng()-destination.lng()).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(origin.lat().toRad()) * Math.cos(destination.lat().toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c; // Distance in km
}
};
});
您应该在需要的地方使用:distance.calculate(a,b)
相关文章:
- 使用返回函数sinde.attr()jquery元素
- 从自执行函数返回函数的Javascript性能命中率
- Node Express Handlebars帮助程序未返回函数的结果
- 未在Firefox中执行PageMethod的返回函数
- 对返回函数的函数感到困惑
- 从承诺返回不返回函数会导致警告
- 从函数返回函数而不调用返回的函数
- Javascript,闭包中的返回函数如何与外部函数连接
- 为什么Coderbyte.com's的Javascript模板喜欢返回函数的原始参数
- 对象函数返回函数而不是值
- 从外部函数(数组)了解返回函数(x)
- 从Javascript类对象返回函数
- 调用Typescript setter don't返回函数,尽管关联的getter可以工作
- 使用依赖注入在 JavaScript 中返回函数
- 通过单击JSP和javascript加载两个返回函数
- 需要说明:无法理解返回函数的javascript
- 简单的onClick返回函数不起作用
- 为什么这个闭包返回函数
- JS函数返回函数供以后使用-未定义参数
- Coffeescription类中的方法返回函数而不是字符串