AngularJS - value Fn

What is the point of the function

function valueFn(value) {return function() {return value;};} 

defined in angular.js.

It is used for ex. in

 var lowercaseFilter = valueFn(lowercase); register('lowercase', lowercaseFilter); 

What is the difference if we used lower case directly, as in

 register('lowercase', lowercase); 

instead of the previous line.

Similarly, in the method

 function ngDirective(directive) { if (isFunction(directive)) { directive = { link: directive } } directive.restrict = directive.restrict || 'AC'; return valueFn(directive); } 

why the last line is not

 return directive; 

but

 return valueFn(directive); 
+4
source share
1 answer

Filters (and some other services) are regular functions, but AngularJS relies heavily on dependency injection, so these filters (functions) are not exposed to as-is clients (as instance objects), but factory functions are created instead. This is done so that the AngularJS DI system can introduce factory function dependencies (and these dependencies are available later in the end).

But there are times when nothing needs to be entered, and all the work of the factory function comes down to returning the previously created value. This applies to lowercaseFilter (and many other filters). Therefore, instead of repeating the same factory function, almost nothing was done, valueFn was created to avoid code repeating. Without it, AngularJS code should contain:

 var lowercaseFilter = function(){ return lowercase; }; var uppercaseFilter = function(){ return uppercase; }; ... 

More simple to write:

 var lowercaseFilter = valueFn(lowercase); var uppercaseFilter = valueFn(uppercase); ... 

In short, I suspect the reason is DRY .

+11
source

All Articles