AngularJS How to call directive function from controller
you can do it with angular pubsub
link: function(scope, element, attrs) {
scope.updateMap = function() {
alert('inside updateMap()');
}
scope.setFn({theDirFn: scope.updateMap});
scope.$on('eventName', function(event, data){
//call directive function here
})
}
function MyCtrl($scope) {
$scope.$broadcast('eventName', data)
}
Starting with the controller, this block creates a setDirectiveFn()
method on the $scope
object in your controller that takes a single parameter (directiveFn
) and then uses that parameter to create a directiveFn()
method on the $scope
object in your controller.
$scope.setDirectiveFn = function(directiveFn) {
$scope.directiveFn = directiveFn;
};
Inside the directive it is creating an updateMap()
method on the scope
object in the directive and then calling the setFn()
method which is mapped to the $scope.setDirectiveFn()
method by this line: <map set-fn="setDirectiveFn(theDirFn)"></map>
in your HTML and this line: scope: { setFn: '&' }
in your directive. It is passing the scope.updateMap()
method which effectively sets $scope.directiveFn()
in your controller equal to scope.updateMap()
in your directive.
link: function(scope, element, attrs) {
scope.updateMap = function() {
alert('inside updateMap()');
}
scope.setFn({theDirFn: scope.updateMap});
}
The button is then calling $scope.directiveFn()
in your controller which has been mapped to scope.updateMap()
in your directive.
<button ng-click="directiveFn()">call directive function</button>