jagdipa
jagdipa

Reputation: 540

Angular directive DOM manipulation dependent on scope variables

I have read that DOM manipulation in angular should be done in the compile function of a directive, and not in the pre-link/post-link/controller. The compile function does not have access to the scope.

My problem is that I want to do DOM manipulation that is dependent on scope variables. For example, I have a list that I am passing into the directive. Within the directive, I am creating a custom select with the list items within it. Where is the right place to manipulate the DOM in this case?

Note that I am not using ng-repeat - I have found it very slow when the list becomes large.

Upvotes: 0

Views: 926

Answers (1)

georgeawg
georgeawg

Reputation: 48968

I don't know where you have read "DOM manipulation in angular should be done in the compile function of a directive". That contradicts the advice of the AngularJS team.

Creating a Directive that Manipulates the DOM

Directives that want to modify the DOM typically use the link option to register DOM listeners as well as update the DOM.

-- AngularJS Developer Guide - Directives - DOM Manipulation

The built-in directives, ng-repeat, ng-if, ng-when, etc. all do their DOM manipulation in the link function.

compile

The compile function deals with transforming the template DOM. Since most directives do not do template transformation, it is not used often.

-- AngularJS $compile Service API Reference -- compile

Upvotes: 2

Related Questions