Typically, we provide a child-directive with a callback function that it can trigger in response to certain events. But in my case, I need to inform the directive about something instead. I'm still using angular 1.4 for now, but plan to upgrade to 1.5 and then eventually to 2. Given this transition, I want to avoid relying on methods like $watch
or $broadcast
.
So, I've identified two potential solutions: 1) utilizing a service and 2) binding a callback function from the child back to the parent.
1) While using a service may seem like the recommended approach, I see two drawbacks:
a) Establishing an entire service for a simple task
b) Requiring $watch
to detect any changes
2) On the other hand, the second solution appears straightforward, but in practice, it has proven more complex than expected, and perhaps even unfeasible :(
Here is a snippet of my test code:
<button ng-click="mycontroller.callback()">Click me</button>
<bar-foo activate-me="mycontroller.callback"></bar-foo>
In this scenario, while mycontroller
does not possess a function called callback
, the bar-foo
directive does
angular.module('HelloApp')
.directive('barFoo', function () {
return {
restrict: 'E',
scope:{
activateMe: '='
},
controller: function ($scope) {
$scope.activateMe = function () {
this.activated = true
}
},
template: '<p ng-if="activated">Activated</p>'
}
});
Is what I'm attempting achievable? Should I resign to the fact that using services
is the sole option for addressing this issue, or are there alternative approaches available?