This is a #worknote.
Scenario
In cases where an attribute directive is needed and a component cannot be used and the desire is for the directive to pass some data to the using parent component.
In a component, we can use &
binding. But in a directive, we need to do the &
work ourselves.
Solution
Directive Controller
function ($scope, $attrs, $parse) {
const exprFn = $parse($attrs.myDirective);
const newScope = $scope.$new(false, $scope);
newScope.variableToPass = 1234;
exprFn(newScope);
newScope.$destroy();
}
Parrent Component
<div my-directive="$ctrl.setValue(variableToPass)"></div>
$attrs is a special object that for each injected component/directive contains the attrs of the attached element.
If
myDirective
is registered asmyDirective
, it will also be in$attrs
object asmyDirective
by the same name.Angular
$parse
service allows us to compile a string representing an AnuglarJs javascript expression into an activation function. That function can be activated which in turn runs that expression in the context of the params given to that functionWe create a new scope so the outside user of the directive can use the parent scope variables also in the provided expression in case needing them. Otherwise we would just do
exprFn({ someVar: 1234 })
new scopes need to be disposed of to prevent leak.
Top comments (0)