7

I am having a weird problem with not being able to use underscore functions inside either the {{}} or inside the ng-repeat and other expressions. My exact test function was

{{_.last([1,2,3,4])}}

... right in the HTML of the page.

I am able to see the correct answer (4) only if I do this in my controller:

$scope._ = _;

I tried to inject _ as a factory into my main application module and then inject that into my controller, but it doen't seem to inject it into the $scope.

Can anyone see the mistake I am making? Or is there a mechanism there that would prevent the underscore library from getting into the $scope? I am using angular v.1.0.7 and a recent version of underscore (not sure of the exact version number, but it is within the last 3 weeks).

2
  • To clarify, I can use underscore fine inside the controller itself. It is only not "visible" in the view (inside of the HTML markup). Commented Jun 28, 2013 at 14:10
  • To anyone reading this in 2015: Please don't do this! Write a function in your controller and use underscore/Ramda/lodash etc. there instead. Injecting these libraries into your view bypasses the safeguards in expressions and is generally a bad idea! Commented Sep 2, 2015 at 17:21

1 Answer 1

5

Angular expressions ({{expression}}) are evaluated against the local $scope, which, in case you have defined a controller, is a $scope object as in function MyCtrl($scope){}.

So, when you use _ in your expressions, the _is evaluated against the $scope, and since $scope.doesn't have a _ member, you expression fails.

So, the only to use _in your views is to make it available on $scope object with: $scope._ = _;.


Btw, when used in browser context, underscore adds _as global object, so it's available throughout your JS. This means that there's no need to "inject _as a factory".

Sign up to request clarification or add additional context in comments.

1 Comment

I was trying the injection because of this thread ( stackoverflow.com/questions/14968297/… ), but it turns out that was to make it available in the controller. Ironically, the answer to my question was in the OP's question, not in the answer I found through the google search. I am now injecting underscore into the $rootScope when the application loads. Thanks for clarifying!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.