How to make lodash work using Angular JS?

I am trying to use lodash using it in ng-repeat directives, as follows:

 <div ng-controller="GridController" ng-repeat="n in _.range(5)"> <div>Hello {{n}}</div> </div> 

Be a GridController :

 IndexModule.controller('GridController', function () { this._ = _ }) 

However, it does not work, and therefore nothing is repeated. If I change the directive to ng-repeat="i in [1,2,3,4,5]" , this will work.

lodash already enabled via <script> in <header> to angular . How can I make it work?

+61
javascript angularjs lodash
May 26 '14 at 3:01
source share
4 answers

I prefer to type '_' globally and injectively for tests, see my answer to this question Use underscore inside controllers

 var myapp = angular.module('myApp', []) // allow DI for use in controllers, unit tests .constant('_', window._) // use in views, ng-repeat="x in _.range(3)" .run(function ($rootScope) { $rootScope._ = window._; }); 
+102
Aug 01 '14 at 18:01
source share

I just wanted to add some clarification to @beret and @wires answers. They definitely helped and got madness from it, but putting the whole process in order could suit someone. This is how I set up angular with lodash and got it working with yoman gulp - angular to work properly

  • bower install lodash --save (This adds to the gazebo and stores the bower json value)

  • change bower json to load lodash to angular. (This helps if you use gulp and do not want to manually put it in index.html, otherwise put it in index.html before the angular link)

  • Make a new constant in the direction of @wires.

 'use strict'; angular.module('stackSample') // lodash support .constant('_', window._); 
  • Injecting into any angular service, filter or controller, just like you:
 .filter('coffeeFilter', ['_', function(_) {...}]); 
  • To pass it into some kind of angular html, just paste it into the controller and assign it a scope variable:
 .controller('SnesController', function ($scope, _) { $scope._ = _; }) 

Hope this helps someone build their site. :)

+53
Apr 17 '15 at 22:43
source share

ng-repeat requires an Angular expression that has access to Angular scope variables. So instead of assigning _ to this assign it to the $scope object that you enter into the controller:

 IndexModule.controller('GridController', function ($scope) { $scope._ = _; }) 

Demo

+28
May 26 '14 at 3:36
source share

I am not sure which version of Angular you are using. It looks like you should have used the controller-like syntax when you use 'this' to access variables in dom.

Here is a solution with this and without using an area. http://plnkr.co/edit/9IybWRrBhlgQAOdAc6fs?p=info

  <body ng-app="myApp" ng-controller="GridController as grid"> <div ng-repeat="n in grid._.range(5)"> <div>Hello {{n}}</div> </div> </body> 
+2
Sep 11 '15 at 1:41
source share



All Articles