Angularjs: insert underscore in $ scope

I had a strange problem: you cannot use underscore functions inside {{}} or inside ng-repeat and other expressions. My exact test function was

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

... right in the HTML page of the page.

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

 $scope._ = _; 

I tried to introduce _ as a factory in my main application module, and then paste it into my controller, but it does not seem to inject it into the $ scope area.

Can anyone see the mistake I'm making? Or is there a mechanism there that would prevent the underscore library from falling into the $ area? I am using angular v.1.0.7 and a recent underscore version (not sure about the exact version number, but it has been in the last 3 weeks).

+6
source share
1 answer

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

So, when you use _ in your expressions, _ is evaluated by the variable $ scope, and since $ scope.doesn't have a member _ , you lose the expression.

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


Btw, when used in a browser context, underscore adds _ as a global object, so it is available throughout your JS. This means that there is no need to "enter _ as a factory".

+5
source

Source: https://habr.com/ru/post/948324/


All Articles