如何测试从控制台的AngularJS服务? [英] How can I test an AngularJS service from the console?

查看:140
本文介绍了如何测试从控制台的AngularJS服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个服务:

angular.module('app').factory('ExampleService', function(){
  this.f1 = function(world){
    return 'Hello '+world;
  }
  return this;
})

我想为从JavaScript控制台测试和调用函数服务的F1()

我怎么能这样做?

推荐答案

于是我发现,你不能简单地调用 angular.injector(['应用'])如果已经存在的喷射器。因为这个函数试图创建一个新的注射器。

So I found out that you can not simply call angular.injector(['app']) if there already exists an injector. Because this function tries to create a new injector.

相反,你必须调用 =喷油angular.element(document.body的).injector()

从检索到的注射器那么你就可以得到什么服务,你用 injector.get喜欢的('服务名称')

From the retrieved injector you can then get whatever service you like with injector.get('ServiceName')

因此​​,在一行的命令是这样的:

So in one line the command would look like this:

angular.element(document.body).injector().get('serviceName')

在这个答案上的更多信息:无法从角检索注射器结果
而更在这里:从传统code



另一个有用的技巧以获取特定元素的 $范围
与在 DOM检查你的开发工具的工具:选择元素,然后运行以下行( $ 1,0 始终选定元素):结果
angular.element($ 0).scope()

More information on that in this answer: Can't retrieve the injector from angular
And even more here: Call Angular JS from legacy code


Another useful trick to get the $scope of a particular element. Select the element with the DOM inspection tool of your developer tools and then run the following line ($0 is always the selected element):
angular.element($0).scope()

这篇关于如何测试从控制台的AngularJS服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆