Reputation: 5632
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?
Upvotes: 6
Views: 1117
Reputation: 304
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>
Upvotes: 0
Reputation: 1501
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.
Upvotes: 0
Reputation: 229
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 recommend an es6 architecture. You can take a look at this
Upvotes: 0
Reputation: 376
I 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.
Upvotes: 11
Reputation: 15922
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
Upvotes: 0
Reputation: 2090
I think it would be better not attaching underscore to angular but use it directly.
Upvotes: 7