How can I expose a method from a directive? I know that I should use attributes for data, but I really want to expose behavior, not data. Something that the parent controller can call.
Let's say my DOM looks like:
<div ng-app="main">
<div ng-controller="MyCtrl">
<button ng-click="call()" >Call</button>
<div id="container" my-directive> </div>
</div>
</div>
JavaScript:
angular.module("main", []).controller("MyCtrl", function($scope) {
$scope.call = function() {
$scope.myfn();
};
}).directive("myDirective", function() {
return {
// scope: {},
controller: function($scope) {
$scope.myfn = function() {
console.log("myfn called");
}
}
};
});
jsFiddle: http://jsfiddle.net/5gDjQ/7/
If the scope
is commented out (i.e. the directive does not have isolated scope), it works just fine. When I press the button, myfn
is called and logs to console.
As soon as I uncomment scope
, it doesn't work. myfn
is defined on child scope and not easily available to the parent.
In my case I think that polluting the parent scope is a bad idea and I would really like to avoid it.
So, how can I expose a function from directive to the parent controller? Or: How can I invoke a method on directive from parent controller?
$scope.$parent.myfn = function() { ... }
, buut you got some better answers down there. – Langdon