如何在angularjs控制器中使用下划线库?
关于这篇文章:AngularJS limitTo by last 2 records有人建议给rootScope分配一个_ variable,这样这个库就可以在应用程序中的所有作用域中使用。
但我不知道该在哪里做。我的意思是,它应该出现在应用程序模块声明中吗?即:
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>
...
我该如何实现这一点?
发布于 2013-02-20 06:33:23
当包含下划线时,它会将自身附加到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
});
发布于 2014-06-02 05:29:27
我使用的是:
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。
发布于 2013-10-16 12:52:58
您还可以查看angular的此模块
https://stackoverflow.com/questions/14968297
复制相似问题