我想在AngularJS视图模板中使用Underscore / Lodash / _.这样我可以使用_如下所示:
<li ng-repeat="number in _.range(100,125)"><!-- Some logic here --></li>
就此而言,我们可以使用Lodash的任何有用功能.
我们可以通过在控制器和指令的$scope中添加_来实现这一点,如下所示:
$scope._ = _;
但我想进行一次性配置/更改,为每个视图模板的每个范围添加_.
我觉得有用的一种方法是:
$rootScope._ = _; //Have this line in .run() method.
这适用于控制器和指令的所有视图.但这不适用于隔离范围指令的视图.我再次必须在指令定义中添加($scope._ = _;).
是否有可以实现此目的的一次性/单一地点更改/配置/代码?
注意:另一个问题How to make lodash work with Angular JS?特别谈到在ng-repeat中使用lodash.但我的问题是在每个视图模板(包括指令视图模板)中使用lodash.这是我发现隔离范围指令的限制.
解决方法
@H_502_38@ 这就是我这样做的方式:步骤1:在index.html中包含underscore-min.js:
<!-- underscore to be included with angular js --> <script src="lib/underscore/underscore-min.js"></script>
步骤2:创建一个’_’服务,您可以将其注入所需的所有控制器:
'use strict'; angular.module('myApp') .factory('_',function($window) { return $window._; // assumes underscore is loaded on the page });
第3步:通过注入’_’在任何你喜欢的地方使用它:
'use strict'; angular.module('myApp') .controller('AppCtrl',function($scope,_) { var test = { x: 10,name: 'Ashish Bajaj' } var 2ndTest = _.clone(test); //use underscore });