在 Angular 控制器中使用下划线 [英] Use underscore inside Angular controllers

查看:32
本文介绍了在 Angular 控制器中使用下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 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) { }

但是我在哪里加载下划线库?我的索引页面上只有 ng-app 指令和对 angular-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>
...  

我如何实现这一目标?

推荐答案

当您包含 Underscore 时,它​​会将自身附加到 window 对象,因此全局可用.

When you include Underscore, it attaches itself to the window object, and so is available globally.

因此您可以按原样从 Angular 代码中使用它.

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
});

这篇关于在 Angular 控制器中使用下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆