注入非角度JS库 [英] Inject non-angular JS libraries
问题描述
在我们的项目中,我们将NPM与Browserify一起用于第三方依赖项管理,该功能与AngularJS结合使用非常好(这要归功于CommonJS模块).
In our project we use NPM together with Browserify for third-party dependency management, which works great in combination with AngularJS (thanks to the CommonJS-modules).
以下代码显示了依赖关系结构,该结构与angular的依赖关系注入非常有用:
The following code shows the dependency-structure, which works great with angular's dependency injection:
(function () {
'use strict';
var moment = require('moment');
var lodash = require('lodash');
var angular = require('angular');
var app = angular.module('myProject', [
require('angular-ui-router'),
require('angular-animate'),
require('angular-resource'),
require('angular-ui-bootstrap'),
require('ng-file-upload'),
require('angular-smart-table'),
]);
app.constant('moment',moment);
app.constant('lodash',lodash);
})();
我的问题是关于 moment 或 lodash 之类的普通javascript库.将它们注入到我的控制器和指令中的最佳方法是什么? app.constant()
方法是可行的方法还是我没有考虑的任何弊端?
My question is about plain-javascript-libraries like moment or lodash. Whats the best way to inject them into my controllers and directive? Is the app.constant()
-approach the way to go or are there any drawbacks I don't consider?
我意识到这个库有很多角度映射器"项目,但是我不希望它们得到足够长的支持,因此宁愿坚持使用原始库.
I realize there are a lot of "angular-mapper" projects for this libraries around, but I don't expect them to get supported long enough and would therefore rather stick to the original-libraries.
推荐答案
您的问题的注释指向正确的方向-首先寻找那些库的有角度的形式.如果没有,那么您可以执行-
The comments to your question do point in the right direction - look for angular'ized forms of those libraries first. If not, then you could do something like -
var lodash = angular.module('lodash', []);
lodash.factory('_', function() {
return window._;
});
,然后使用此模块依赖性并将"_"插入您的控制器和服务.
and then use this module dependency and inject '_' in you controllers and services.
即使您使用app.constant
,它仍然可以作为依赖项注入".我猜这种工厂"方式为您提供了更多的灵活性.
Even if you use app.constant
, it can still be 'injected' as a dependency. The 'factory' way gives you a bit more flexibility I guess.
这篇关于注入非角度JS库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!