使用角度控制器内部下划线 [英] Use underscore inside Angular controllers
问题描述
我如何使用下划线库angularjs控制器内部?
How do I use underscore library inside angularjs controllers?
在这篇文章: AngularJS limitTo由过去的2条
有人建议到_变量分配给rootScope使该库将提供给应用程序内的所有范围。
On this post: AngularJS limitTo by last 2 records somebody suggested to assign an _ variable to the rootScope so that the library will be available to all the scopes within the app.
但我不清楚的地方去做。我的意思是它应该走在应用程序模块声明?即:
But I'm not clear where to do it. I mean should it go on the app module declaration? i.e:
var myapp = angular.module('offersApp', [])
.config(['$rootScope', function($rootScope) { }
但后来我在哪里加载强调的lib?我只是有我的索引页面上的NG-程序指令和脚本参考两个角js和下划线库?
But then where do I load underscore lib? I just have on my index page the ng-app directive and script reference to both the angular-js and underscore libs?
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>
...
我如何做到这一点?
How do I achieve this?
推荐答案
在包括下划线,它重视自身到窗口
对象,所以是全球上市。
When you include Underscore, it attaches itself to the window
object, and so is available globally.
所以,你可以用它从角code原样。
So you can use it from Angular code as-is.
您也可以包起来的服务或一个工厂,如果你想它被注入:
You can also wrap it up in a service or a factory, if you'd like it to be injected:
var underscore = angular.module('underscore', []);
underscore.factory('_', ['$window', function($window) {
return $window._; // assumes underscore has already been loaded on the page
}]);
然后你就可以要求 _
您的应用程序的模块中:
And then you can ask for the _
in your app's module:
// 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
});
这篇关于使用角度控制器内部下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!