There is a unique situation I am trying to tackle where I need to use $broadcast
within a directive's linking function that has an isolated scope. Unfortunately, broadcasting from inside an isolated scope becomes challenging as the directive scope does not inherit from the parent scope, as explained in this source.
I am aware that setting scope: false
on my directive would cause it to use the parent's scope, which could lead to naming collisions and reduce reusability due to crowding of the parent scope.
Considering this, I wonder if using scope: false
on a directive meant for reuse might have further drawbacks beyond organizational concerns. Is it just about preference and cleanliness or are there more negative implications?
As far as I know, there seems to be no other method than broadcasting inside a directive's linking function to achieve the desired functionality, apart from perhaps modifying a service (which isn't feasible given the parent scope hierarchy). Therefore, using $broadcast
appears to be the only available option at the moment. Any insights would be greatly appreciated.
Thank you!
EDIT: Just to clarify, I aim to broadcast from the isolated scope downwards to the children of the parent scope:
JS
.controller('parent', function ($scope) {
$scope.parent = 'parentProperty';
})
.directive('isolate', function() {
return {
scope: {},
template: '<div ng-click="click()">Click</div>',
link: function (scope) {
scope.click = function () {
console.log('clicked,but no broadcast');
scope.$broadcast('event', 'string');
}
}
};
})
.directive('child', function () {
return {
link: function(scope) {
scope.$on('event', function (e, event) {
console.log(event);
});
}
};
});
HTML
<body ng-controller="parent">
<div isolate>Click me to broadcast
</div>
<div child>
</div>
</body>