Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

ng-attr- used for custom directive. If expression is undefined, still fires directive link function, even though the directive is not added in the DOM. #16441

Closed
piyushsh opened this issue Feb 7, 2018 · 2 comments

Comments

@piyushsh
Copy link

piyushsh commented Feb 7, 2018

I'm submitting a bug, regarding ng-attr- directive, used to conditionally add directive (as an attribute), if expression is undefined, still fires link function of the directive, even though directive is not added in the DOM.

Current behavior:
Refer plunker

  • Added conditional directive (as an attribute), using ng-attr-test-directive (as mentioned in plunker).
  • Even though ng-attr- expression is undefined and directive is not added in the DOM, the link function of the directive is fired (check console while executing plunker)
    image

Expected / new behavior:
When ng-attr- expression is undefined,

  • It shouldn't add directive to the DOM.
  • It should not call link function of the directive as well.

Minimal reproduction of the problem with instructions:
Please refer plunker
Same repo steps as mentioned in Current behavior.

AngularJS version: 1.6.4
Yes it is an issue.

Browser: [all | Chrome 63.0.3239.132 | Firefox |
OS: Windows 10

@gkalpak
Copy link
Member

gkalpak commented Feb 7, 2018

This is expected behavior I'm afraid. ng-attr- is not a way to conditionally apply directives. Even if it allows conditionally adding/removing an attribute, this behavior depends on evaluating an expression in the context of the current scope, which cannot happen during the compilation phase (when the directives on an element are collected and processed).

One could argue that ng-attr-foo should not be treated as if the foo property was present, but, since the main purpose of ng-attr-foo is to set the foo attribute using an interpolated expression (in cases where it is not allowed to directly set foo to a string containing interpolation markers), I think the current behavior is reasonable.

You need to devise a different way (depending on your usecase) to conditionally apply directives (e.g. use ng-switch and have two versions of the HTML; one with the directive and one without, or have a terminal directive with high priority that evaluates the expression during the linking phase, applies the necessary directive(s) and compiles the element).

@piyushsh
Copy link
Author

piyushsh commented Feb 8, 2018

@gkalpak Thanks for your reply, makes sense.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants