Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: Inject underscore into $scope

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).

like image 549
electrichead Avatar asked Jun 28 '13 14:06

electrichead


1 Answers

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".

like image 105
Stewie Avatar answered Sep 29 '22 11:09

Stewie