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).
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With