AngularJs:视图模板中具有下划线/Lodash/_ [英] AngularJs: Have Underscore/Lodash/_ in the view template
问题描述
我正在尝试在AngularJS视图模板中使用Underscore/Lodash/_.这样,我可以使用_,如下所示:
I am trying to have the Underscore/Lodash/_ available in the AngularJS view template. This way I can use _ like shown below:
<li ng-repeat="number in _.range(100, 125)"><!-- Some logic here --></li>
为此,我们可以使用Lodash的任何有用功能.
And for that matter, we can use any of those useful functions of Lodash.
我们可以通过在控制器和指令的$ scope中添加_来实现此目的,如下所示:
We can achieve this by just adding _ to the $scope of the controllers and directives as shown below:
$scope._ = _;
但是我想进行一次配置/更改,以便为每个视图模板的每个作用域添加_.
But I would like to have a one-time configuration/change that adds _ to every scope for every view templates.
我发现有用的一种方法是:
One approach I found useful is:
$rootScope._ = _; //Have this line in .run() method.
这对于控制器和指令的所有视图都适用.但这不适用于隔离范围的指令的视图.我再次必须在指令定义中添加($ scope._ = _;).
This works fine for all the views of controllers and directives. But this is not working for views of isolated scoped directives. I again have to add ($scope._ = _;) in the directive definition.
是否可以通过一次/单处更改/配置/代码来实现这一目标?
Is there a one-time/single-place change/configuration/code that can achieve this?
注意:另一个问题如何使lodash与Angular JS一起使用?专门讨论在ng-repeat中使用lodash.但是我的问题是关于在每个视图模板(包括指令视图模板)中使用lodash.那就是我发现隔离范围指令的局限性所在.
Note: The other question How to make lodash work with Angular JS? talks specifically about using lodash in ng-repeat. But my question is about using lodash in every view template (including directive view template). That is where I found an limitation with isolated scoped directive.
推荐答案
这是我的方法:
步骤1:在您的index.html中添加underscore-min.js:
Step #1: include underscore-min.js in your index.html:
<!-- underscore to be included with angular js -->
<script src="lib/underscore/underscore-min.js"></script>
第2步:创建一个"_"服务,您可以将其插入所需的所有控制器中:
Step #2: Create a '_' service that you can inject into all the controllers you need:
'use strict';
angular.module('myApp')
.factory('_', function($window) {
return $window._; // assumes underscore is loaded on the page
});
第3步:注入"_"以在任意位置使用它:
Step #3: Use it where ever you like by injecting '_':
'use strict';
angular.module('myApp')
.controller('AppCtrl', function($scope, _) {
var test = {
x: 10,
name: 'Ashish Bajaj'
}
var 2ndTest = _.clone(test); //use underscore
});
这篇关于AngularJs:视图模板中具有下划线/Lodash/_的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!