angularjs – 角度注射器上下划线的含义

我一直在为一些Angular组件编写测试,使用我刚才在google上找到的语法:

describe('Directive: myDir',function () {
     beforeEach(module('myApp'));
     beforeEach(module('app/views/my_template.html'));
     beforeEach(inject(function ($rootScope,_$compile_,$templateCache) {
         $templateCache.put('views/my_template.html',$templateCache.get('app/views/my_template.html'));

         var scope,$compile;
         scope = $rootScope;
         $compile = _$compile_;
         element = angular.element("<div my-dir class='my-dir'></div>");
     }));

     it('does things',function () {
         $compile(element)(scope);
         scope.$digest();
     });
 });

我的问题是关于_ $compile_的注入.它与$compile有什么不同.我为什么要这样做呢?为什么$compile被重新定义,为什么我不能简单地编译我注入的$compile?

解决方法

Angular official tutorial(测试部分):

The injector ignores leading and trailing underscores here (i.e. $httpBackend). This allows us to inject a service but then attach it to a variable with the same name as the service.

在您的示例中,您可以将变量$compile重命名为编译,然后从参数名称中删除下划线.事实上,你这样做的范围是因为$rootScope仍然没有下划线.

我个人喜欢在测试中保留Angular内置服务的名称,以便在浏览代码时轻松发现它们.

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...