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?
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 ofscope: { localFn:'&myAttr' }
, then isolate scope propertylocalFn
will point to a function wrapper for thecount = 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 isincrement(amount)
then we can specify the amount value by calling the localFn aslocalFn({amount: 22})
(emphasis mine)