Wednesday, September 6, 2017

How to use underscore in angular ?

Steps:

1) Install underscore
bower install underscore --save

2) Include the script in index.html. Make sure it loads before angular js.

<script src="/bower_components/underscore/underscore.js"></script>
<script src="/bower_components/angular/angular.js"></script>
<script src="/bower_components/angular-route/angular-route.js"></script>

3) Underscore when included attaches to the window object. So it is available globally. One can use it from Angular code directly. However if you want this to be injected then can be wrapped in a service or factory. Check the code below.

Go to you application module. And add the following.

var underscore = angular.module('underscore', []);
underscore.factory('_', ['$window', function($window) {
  return $window._; // assumes underscore has already been loaded on the page
}]);

// Declare as a dependency of the module
angular
  .module('angularUnderscoreExample', [
    'underscore'
  ]);

//Inject when required
angular.module('angularUnderscoreExample')
  .controller('MainCtrl', ['$scope', '_',
  function ($scope, _) {

   _(3).times(function(n){
      console.log(n);
    });

  }])

4) If you want to get complete sample integration code please check the github url below.

https://github.com/fullstacktechnos/angular-underscore-demo


No comments:

Post a Comment