如何在 angularjs 控制器中使用下划线库?
在这篇文章中:AngularJS limitTo 按最后 2 条记录 https://stackoverflow.com/questions/11943130/angularjs-limitto-by-last-2-records有人建议将 _ 变量分配给 rootScope,以便该库可供应用程序内的所有范围使用。
但我不清楚在哪里做。我的意思是它应该放在应用程序模块声明中吗? IE:
var myapp = angular.module('offersApp', [])
.config(['$rootScope', function($rootScope) { }
但是那么我在哪里加载下划线库呢?我的索引页上只有 ng-app 指令和对 angular-js 和 underscore 库的脚本引用?
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>
...
我该如何实现这一目标?
当您包含下划线时,它会将自己附加到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
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)