Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of underscores on arguments (of the inject function)?

I've been writing tests for some Angular components, using a syntax that I found on google a while ago:

 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();
     });
 });

My question is specifically about the injection of _$compile_. How is it different from just $compile. Why would I need to do it this way? Why does $compile get redefined, why can't I simply compile with a $compile I inject?

like image 232
Abraham P Avatar asked Jul 31 '13 23:07

Abraham P


1 Answers

From the Angular official tutorial (Test section):

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.

In your example, you could rename the variable $compile as, say, compile and then remove the underscores from the parameter name. In fact, you did that to scope so $rootScope remained underscore-free.

Personally I like to keep the name of Angular built-in services in my tests so they can be easily spotted while skimming through the code.

like image 138
Michael Benford Avatar answered Nov 30 '22 13:11

Michael Benford