Search code examples
angularjsangular-directive

Understanding function call in element directives in angular js


I was going through angular js docs and trying to understand following piece of code:-

<div ng-app="choreApp">
  <div ng-controller="ChoreCtrl">
    <kid done="logChore(chore)"></kid>
        </div>
</div>

 app.controller("ChoreCtrl", function($scope){
 $scope.logChore = function(chore){
 alert(chore + " is done!");
 };
 });

 app.directive("kid", function() {
 return {
   restrict: "E",
   scope: {
    done: "&"
  },
template: '<input type="text" ng-model="chore">' +
  '{{chore}}' +
  '<div class="button" ng-click="done({chore: chore})">I\'m done</div>'
  };
});

I went through the documents at least dozen times but still not convinced how {core: core} is working and how is the function logChore(core) invoked.

Can someone help me understand how above is working?


Solution

  • Well, it's explained in the documentation:

    & 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 <widget my-attr="count = count + value"> 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)