Communication between controller and directive function
How to pass parameters to a function from a directive
HTML
<div ng-app="myApp" ng-controller="DemoCtrl">
<!-- WARNING : parameters must match params property name. Here only param 2 is used -->
<demo-communication demo-on-click="clickHandler(param2)" ></demo-communication>
<div ng-if="callParam">called with param {{callParam}}</div>
</div>
JavaScript
angular.module('myApp', [])
.directive('demoCommunication',[ function () {
return {
//Define 3 inputs and 1 button. The button click call the btnCliked function defined in directive controller
template : '<input ng-model="paramValue1" type="text" placeholder="param 1"/><br>' +
'<input ng-model="paramValue2" type="text" placeholder="param 2"/><br> ' +
'<input ng-model="paramValue3" type="text" placeholder="param 3"/><br> ' +
'<button ng-click="btnClicked()">click me</button>',
scope: {
demoOnClick: '&'
},
restrict: 'E',
link: function ($scope, $element, $attrs) {
},
controller: function ($scope) {
$scope.btnClicked = function () {
//Call controller function with params as Object
$scope.demoOnClick(
{
param1 : $scope.paramValue1,
param2 : $scope.paramValue2,
param3 : $scope.paramValue3
});
};
}
};
}]
).controller('DemoCtrl', function ($scope) {
//Define directive callback. Only 1 param is used.
$scope.clickHandler = function (param) {
debugger;
$scope.callParam = param;
};
});