如何在 angularjs Controller 中使用下划线库?
在这篇文章中:AngularJS limitTo by last 2 records 有人建议为 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 代码中使用它。
如果您希望它被注入(inject),您也可以将其包装在服务或工厂中:
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
});
关于javascript - 在 Angular Controller 中使用下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14968297/