AngularJs: Underline / Lodash / _ in view template

I am trying to use Underscore / Lodash / _ in an AngularJS view template. That way I can use _ as shown below:

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

And in this regard, we can use any of these useful Lodash features.

We can achieve this by simply 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 each area for each view template.

One approach that I found useful is:

 $rootScope._ = _; //Have this line in .run() method. 

This is great for all kinds of controllers and directives. But this does not work for viewing isolated directives. Again I have to add ($ scope._ = _;) to the directive definition.

Is there a one-time / one-place change / configuration / code that can do this?

Note: Another question. How to make lodash work using Angular JS? , talks about using lodash in ng-repeat. But my question is about using lodash in every presentation template (including the directive presentation template). This is where I found the constraint with the limited area highlighted.

+5
source share
1 answer

Here is how I did it:

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 the "_" service, which you can enter 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 whenever you want by adding "_":

 'use strict'; angular.module('myApp') .controller('AppCtrl', function($scope, _) { var test = { x: 10, name: 'Ashish Bajaj' } var 2ndTest = _.clone(test); //use underscore }); 
0
source

All Articles