Activating Outbound Attribute Expression in AngualrJs Directive

elpddev

Eyal Lapid

Posted on January 7, 2021

Activating Outbound Attribute Expression in AngualrJs Directive

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();
}
Enter fullscreen mode Exit fullscreen mode

Parrent Component

<div my-directive="$ctrl.setValue(variableToPass)"></div>
Enter fullscreen mode Exit fullscreen mode
  • $attrs is a special object that for each injected component/directive contains the attrs of the attached element.

  • If myDirective is registered as myDirective, it will also be in $attrs object as myDirective 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 function

  • We 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.

💖 💪 🙅 🚩
elpddev
Eyal Lapid

Posted on January 7, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related