Here is a skeleton app that demonstrates how you can call parent controller functions from directives while using isolate scope to avoid tight coupling (which enhances reusability):
JS:
angular.module('myApp', [])
.controller('MyController', function($scope){
$scope.showAlert = function(value){
alert('Called from directive: ' + value);
};
})
.directive('myDirective', function(){
return {
restrict: 'E',
scope: {
alert: '&'
},
controller: function($scope){
$scope.value = 'directive scope value';
},
template: '<button ng-click="alert({message: value})">Alert</button>'
}
});
HTML:
<body ng-app="myApp" ng-controller="MyController">
<my-directive alert="showAlert(message)"></my-directive>
</body>
The thing to focus on is the use of the &
symbol in the scope: { ... }
setting of the directive. In this case, it provide you with the ability to name the controller function in the alert
attribute of your directive declaration in the HTML.
That function can then be called from the template of the directive.
Using isolate scope is a common pain point when learning about directives in Angular, but it is well-worth taking the time to wrap your head around.
Regarding the use of &
in particular, I found this video to be especially helpful.