Pab*_*blo 125 javascript underscore.js angularjs
如何在angularjs控制器中使用下划线库?
在这篇文章中:AngularJS limitTo最后2条记录 有人建议将一个_变量分配给rootScope,以便该库可供应用程序中的所有范围使用.
但我不清楚在哪里做.我的意思是应该继续app模块声明吗?即:
var myapp = angular.module('offersApp', [])
.config(['$rootScope', function($rootScope) { }
Run Code Online (Sandbox Code Playgroud)
但那我在哪里加载下划线库?我只是在我的索引页面上有ng-app指令和对angular-js和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>
...
Run Code Online (Sandbox Code Playgroud)
我该如何实现这一目标?
sat*_*run 230
当您包含Underscore时,它会将自身附加到window对象上,因此全局可用.
因此,您可以按原样使用Angular代码.
如果您希望将其注入,您也可以将其包装在服务或工厂中:
var underscore = angular.module('underscore', []);
underscore.factory('_', ['$window', function($window) {
return $window._; // assumes underscore has already been loaded on the page
}]);
Run Code Online (Sandbox Code Playgroud)
然后你可以_在你的应用程序模块中询问:
// 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
});
Run Code Online (Sandbox Code Playgroud)
uni*_*ify 32
我在这里实现了@ satchmorun的建议:https: //github.com/andresesfm/angular-underscore-module
要使用它:
确保在项目中包含了underscore.js
<script src="bower_components/underscore/underscore.js">
Run Code Online (Sandbox Code Playgroud)得到它:
bower install angular-underscore-module
Run Code Online (Sandbox Code Playgroud)将angular-underscore-module.js添加到主文件(index.html)
<script src="bower_components/angular-underscore-module/angular-underscore-module.js"></script>
Run Code Online (Sandbox Code Playgroud)在应用程序定义中将模块添加为依赖项
var myapp = angular.module('MyApp', ['underscore'])
Run Code Online (Sandbox Code Playgroud)要使用,请将其作为注入依赖项添加到Controller/Service中,并且可以使用它
angular.module('MyApp').controller('MyCtrl', function ($scope, _) {
...
//Use underscore
_.each(...);
...
Run Code Online (Sandbox Code Playgroud)wir*_*res 31
我用这个:
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 Code Online (Sandbox Code Playgroud)
请参阅https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection,了解更多信息run.
| 归档时间: |
|
| 查看次数: |
98006 次 |
| 最近记录: |