6

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.

Community
  • 1
  • 1
Vijey
  • 6,536
  • 7
  • 43
  • 50
  • 2
    Create a constant and inject where needed ? Doesn't really make sense to me putting library functions in markup though – charlietfl May 07 '15 at 13:20
  • possible duplicate of [How to make lodash work with Angular JS?](http://stackoverflow.com/questions/23862119/how-to-make-lodash-work-with-angular-js) – victorkt May 07 '15 at 13:25
  • 4
    I highly recommend using a filter instead of passing this to your view. See: http://toddmotto.com/everything-about-custom-filters-in-angular-js/ for more. – JMP May 07 '15 at 13:53

1 Answers1

0

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

});
Ashish
  • 595
  • 4
  • 12