简体   繁体   中英

Attaching underscore or lodash to angular

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?

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.

我认为最好不要在 angular 上附加下划线,而是直接使用它。

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 recommend 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM