在Angular控制器中使用下划线
如何在angularjs控制器中使用下划线库?
在这篇文章中: AngularJS limitTo最后2条logging有人build议将一个_variables分配给rootScope,以便该库可用于应用程序内的所有范围。
但我不清楚在哪里做。 我的意思是应该在应用程序模块声明? 即:
var myapp = angular.module('offersApp', []) .config(['$rootScope', function($rootScope) { } 但是,我在哪里加载下划线库? 我只是在我的索引页上的ng-app指令和脚本引用到angular-js和下划线库?
  index.html : 
 <head> </head> <body ng-app="offersApp"> ... <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="scripts/vendor/angular.js"></script> <script src="scripts/vendor/underscore.js"></script> ... 
我如何做到这一点?
 如果包含Underscore,则会将其自身附加到window对象,因此全局可用。 
所以你可以直接使用Angular代码。
你也可以把它包装在一个服务或工厂,如果你想要注入它:
 var underscore = angular.module('underscore', []); underscore.factory('_', ['$window', function($window) { return $window._; // assumes underscore has already been loaded on the page }]); 
 然后你可以在你的应用程序模块中请求_ 
 // Declare it as a dependency of your module var app = angular.module('app', ['underscore']); // And then inject it where you need it app.controller('Ctrl', function($scope, _) { // do stuff }); 
我在这里实施了@ satchmorun的build议: https : //github.com/andresesfm/angular-underscore-module
要使用它:
- 
确保你的项目中包含了underscore.js <script src="bower_components/underscore/underscore.js">
- 
得到它: bower install angular-underscore-module
- 
将angular-underscore-module.js添加到主文件(index.html) <script src="bower_components/angular-underscore-module/angular-underscore-module.js"></script>
- 
将模块作为应用程序定义中的依赖项添加 var myapp = angular.module('MyApp', ['underscore'])
- 
要使用,作为注入的依赖项添加到您的控制器/服务,并准备使用 angular.module('MyApp').controller('MyCtrl', function ($scope, _) { ... //Use underscore _.each(...); ...
我使用这个:
 var myapp = angular.module('myApp', []) // allow DI for use in controllers, unit tests .constant('_', window._) // use in views, ng-repeat="x in _.range(3)" .run(function ($rootScope) { $rootScope._ = window._; }); 
 有关run更多信息,请参阅https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection关于中途。; 
你也可以看看这个模块的angular度
如果你不介意使用lodash,那么试试https://github.com/rockabox/ng-lodash它将完全包装lodash,所以它是唯一的依赖,你不需要加载任何其他脚本文件,如lodash。;
Lodash完全不在窗口范围内,也不希望它在你的模块之前被加载。
你可以使用这个模块 – > https://github.com/jiahut/ng.lodash
 这是为了lodash所以underscore