AngularJs: Have Underscore/Lodash/_ in the view template

淺唱寂寞╮ 提交于 2019-12-23 09:57:34

问题


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>

And for that matter, we can use any of those useful functions of Lodash.

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.

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?

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:


This is how I did this:

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>

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

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

});


来源:https://stackoverflow.com/questions/30102068/angularjs-have-underscore-lodash-in-the-view-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!