【问题标题】:AngularJs: Have Underscore/Lodash/_ in the view templateAngularJs:在视图模板中有下划线/Lodash/_
【发布时间】:2015-07-18 02:02:35
【问题描述】:

我正在尝试在 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。这就是我发现隔离作用域指令的局限性所在。

【问题讨论】:

标签: angularjs lodash


【解决方案1】:

我就是这样做的:

第 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

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多