DEV Community

Cover image for Activating Outbound Attribute Expression in AngualrJs Directive
Eyal Lapid
Eyal Lapid

Posted on • Edited on

1 1

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs