What are $ locals in AngularJS expressions?

AngularJS Expression Developer Guide mentions something called $locals :

Access to the context object is possible using the identifier this and locals using locators $ locals.

I don’t understand what the “locals object” is, and I can no longer find the information about $ locals in the docs. What is the purpose? How do you handle this?

+6
source share
2 answers

The corresponding commit where you can find more information about this is this one , which also refers to a question asking for $ locals.

In short, when passing a parameter to a directive using '&' so that the directive can execute some code if necessary (for example, when you use ng-click="doSomething()" ), the directive can pass information to the caller using local values.

For example, you can use ng-click="doSomething($event)" , where $ event is not an attribute of the scope, but the value passed by the ng-click directive.

Instead of accessing each "local" value passed individually by directive, you can access all of them at once using $locals .

More information on how to pass local values ​​from directives can be found in the directives documentation:

& or & attr - provides a way to execute an expression in the context of the parent scope. If attr is not specified, the attribute name is assumed to match the local name. The defined and visible scope definition is: {localFn: '& myAttr'}, then the isolate scope property localFn will point to the function wrapper for the expression count = count + value. It is often desirable to transfer data from an isolated scope through an expression to the parent area, this can be done by passing a map of local variable names and values ​​to the shell of the expression fn. For example, if the expression is increment(amount) , then we can specify the value of the sum by calling localFn as localFn ({amount: 22})

(my emphasis)

In the above example, all {amount: 22} objects passed by the directive are accessible using $ locals, and you can use increment($locals.amount)

+5
source

See this test for a description of the functionality that appeared from Issue 13247 .

Also consider this example directive with a callback:

 // JS angular.module('app', []) .controller('AppCtrl', function($scope) { $scope.log = function(locals) { console.log(locals); }; }) .component('fooBar', { template: "", bindings: { cb: '&'}, controller: function() { this.a = 1; this.b = 2; this.c = 3; this.cb(this); } }); // HTML <body ng-app="app" ng-controller="AppCtrl"> <foo-bar cb="log($locals)">foobar</foo-bar> </body> 
+2
source

All Articles