如何在angularjs控制器中使用下划线库?
关于此帖子:AngularJSlimitTo的最后2条记录建议有人为rootScope分配一个_变量,以便该库可用于应用程序中的所有范围。
但我不清楚该在哪里做。我的意思是应该在应用程序模块声明中继续吗?即:
var myapp = angular.module('offersApp', []) .config(['$rootScope', function($rootScope) { }
但是,我该在哪里加载下划线lib?我的索引页面上只有ng-app指令和对angular-js和下划线库的脚本引用吗?
index.html:
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对象上,因此在全局范围内都可用。
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 });