Angular: Confusing and non-symmetrical callback with expression binding
http://angularjs.org/
HTML
<div ng-controller="TheController">
<sample-directive the-callback="informParent(theParamX)">
Nice
</sample-directive>
Received Value: {{valueReceivedFromDirective}}
</div>
JavaScript
var theApp = angular.module('theApp',[]);
theApp.directive('sampleDirective', function() {
return {
restrict: 'E',
transclude: true,
scope : {
theCallback : '&'
},
template:
'<div>' +
'<div ng-transclude></div>' +
'<hr/>' +
'<div>Comments: <input ng-model="comments" ng-init="comments=\'Great\'"/></div>' +
'<div><button ng-click="theCallback({theParam: comments})">Click</button></div>' +
'</div>'
};
});
theApp.controller('TheController', ['$scope', function($scope) {
$scope.valueReceivedFromDirective = '';
// If in case we need to reference a controller's property with same name as directive's parameter
// in the callback, there's no way to reference that controller's property.
// That is, this can't be referenced in the-callback
$scope.theParam = 'Blah';
// The name must be different from the directive's parameter name:
$scope.theParamX = 'Meh'; // this can now be referenced in the directive's callback
$scope.informParent = function(valuePassed) {
// code below is symmetrical to the directive's callback. however, it won't work
// $scope.valueFromDirective = valuePassed.comments;
// so should use this:
$scope.valueReceivedFromDirective = valuePassed;
};
}]);