What are $locals in AngularJS expressions?

2020-07-06 08:13发布

AngularJS Developer Guide on Expressions mentions something named $locals:

It is possible to access the context object using the identifier this and the locals object using the identifier $locals.

I don't understand what "locals object" is and I can't find any more info on $locals in docs. What is it's purpose? How do you operate on it?

标签: angularjs
2条回答
可以哭但决不认输i
2楼-- · 2020-07-06 08:22

See this test describing functionality that came about from Issue 13247.

Also consider this example of a 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>
查看更多
欢心
3楼-- · 2020-07-06 08:37

The relevant commit where to find more information about it is this one, which also links to the issue asking to introduce $locals.

In short, when passing a parameter to a directive using '&', in order for the directive to be able to execute some code when needed (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 a value passed by the ng-click directive.

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

More information on how to pass local values from the directive is available in the documentation on directives:

& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22})

(emphasis mine)

In the above axample, the entire object {amount: 22} passed by the directive is available using $locals, and you could thus use increment($locals.amount)

查看更多
登录 后发表回答