Reputation: 14216
I am trying to set up a click function on the outside of the directive to change something in the inside. It seems it's easy to pass a click function outwards, however i need an event outside of the directive to call a function inside of it to update something.
So I have a click function outside the directive
$scope.clickOutisde = function(){
//fire event inside
}
I want to pass it in (I guess)
scope: {
updateFn: '='
}
And on the directive itself
update-fn="clickOutisde"
And inside the directive controller
$scope.updateFn = function(){
console.log("hit!");
}
So the intended effect is I would click function on the outside which would cause a function inside the directive controller to fire. I know it's a bit of a weird set up - but I'm wondering if something like this is possible (as this is not working). Thanks!
Upvotes: 0
Views: 333
Reputation: 17064
The straightforward way to achieve what you want is using emit/broadcast
and I try to steer clear from those as much as possible.
What you can do, is have a wrapper object with a boolean inside and change its value every time the function is triggered, and have that wrapper object passed to the directive and keep watch on it:
Controller + Directive:
myApp.directive('myDirective', function() {
return {
scope: {
functionWrapper: "="
},
template: 'inside directive',
link: function (scope, element, attr) {
scope.$watch(function() {
return scope.functionWrapper.flag;
}, function(newVal, oldVal) {
console.log('function fired');
});
}
}
});
function MyCtrl($scope) {
$scope.functionWrapper = { flag : false };
$scope.func = function () {
console.log('firing in controller');
$scope.functionWrapper.flag = !$scope.functionWrapper.flag;
}
}
HTML:
<div my-directive function-wrapper="functionWrapper"></div>
Upvotes: 1