AngularJs:在视图模板中有Underscore/Lodash/_

Vij*_*jey 6 angularjs lodash

我想在AngularJS视图模板中使用Underscore/Lodash/_.这样我可以使用_如下所示:

<li ng-repeat="number in _.range(100, 125)"><!-- Some logic here --></li>
Run Code Online (Sandbox Code Playgroud)

就此而言,我们可以使用Lodash的任何有用功能.

我们可以通过在控制器和指令的$ scope中添加_来实现这一点,如下所示:

$scope._ = _;
Run Code Online (Sandbox Code Playgroud)

但我想进行一次性配置/更改,为每个视图模板的每个范围添加_.

我觉得有用的一种方法是:

$rootScope._ = _; //Have this line in .run() method.
Run Code Online (Sandbox Code Playgroud)

这适用于控制器和指令的所有视图.但这不适用于隔离范围指令的视图.我再次必须在指令定义中添加($ scope._ = _;).

是否有可以实现此目的的一次性/单一地点更改/配置/代码?

注意:另一个问题如何使lodash与Angular JS一起使用?专门讨论在ng-repeat中使用lodash.但我的问题是在每个视图模板(包括指令视图模板)中使用lodash.这是我发现隔离范围指令的限制.

Ash*_*ish 0

我就是这样做的:

步骤#1:在你的index.html中包含underscore-min.js:

<!-- underscore to be included with angular js -->
<script src="lib/underscore/underscore-min.js"></script>
Run Code Online (Sandbox Code Playgroud)

步骤#2:创建一个“_”服务,您可以将其注入到您需要的所有控制器中:

'use strict';

angular.module('myApp')
.factory('_', function($window) {
    return $window._; // assumes underscore is loaded on the page
});
Run Code Online (Sandbox Code Playgroud)

步骤#3:通过注入“_”在任何你喜欢的地方使用它:

'use strict';

angular.module('myApp')

.controller('AppCtrl', function($scope, _) {

  var test = {
    x: 10,
    name: 'Ashish Bajaj'
  }

  var 2ndTest = _.clone(test); //use underscore

});
Run Code Online (Sandbox Code Playgroud)