Is it ok to attach underscore.js variable to angular variable? so I can call underscore like: angular._
? Since underscore is less likely to be mocked at testing and we can't declare global variables?
if so, which part of my angular.js application should I add it?
Is it ok to attach underscore.js variable to angular variable? so I can call underscore like: angular._
? Since underscore is less likely to be mocked at testing and we can't declare global variables?
if so, which part of my angular.js application should I add it?
Share Improve this question edited Jan 14, 2020 at 21:38 SoEzPz 15.9k8 gold badges64 silver badges66 bronze badges asked Jul 9, 2015 at 8:53 Louie AlmedaLouie Almeda 5,63234 silver badges41 bronze badges 7-
just
angular._ = _;
– dfsq Commented Jul 9, 2015 at 9:10 - 1 Yes it's easy to set it, but my question is: is it ok? :) – Louie Almeda Commented Jul 9, 2015 at 9:16
-
Isn't
angular
a global variable? Can't you treat_
the same? – Davin Tryon Commented Jul 9, 2015 at 9:17 -
Yes, it's ok. Does it make sense? - not sure. Just use
_
as is or wrap it in the service likeutils
which basically exposeswindow._
. – dfsq Commented Jul 9, 2015 at 9:23 - Wouldn't it be better to create a wrapper service for underscore that you can just inject where needed? – Nat Wallbank Commented Jul 14, 2015 at 9:19
6 Answers
Reset to default 11I prefer to create a wrapper service in it's own injectable module like such:
angular.module('underscore.service', [])
.factory('_', function () {
return window._; // assumes underscore has already been loaded on the page
});
As noted, you should include underscore.js before angular in your html as you typically would.
This approach allows makes underscore accessible in a testing environment.
I think it would be better not attaching underscore to angular but use it directly.
The best way I have seen to do this is dependency injecting it.
check out this link to ng-underscore link
or
this link angular-underscore link
If you use ES6 modules you can just import it, if you use the iife approach you can register it as a constant and later inject it
angular.module("app").constant("_", _);
Still I would remend an es6 architecture. You can take a look at this
What testing suite are u going to be using?
If u are using karma, u can add any third party lib in the karma config under the files option. These files will be available in the browser and accessible to your tests. No need to wrap the lib in an angular service or attach it to angular.
If you whant to use underscore you can just simply add it to your scope
Do the following in you controller
$scope._ = _;
now you use all underscore features inside you html template like
<div ng-repeat="value in _.filter(list, ...)"></div>