简体   繁体   中英

In angularjs, when making a directive, is there a way to manipulate the DOM of the template using the link function?

Let's say I'm creating a dynamic directive in angularjs. I want to use the link function to manipulate the DOM of the template html based on the arguments.

So in vanilla javascript, I would do something like the following:

var template = ... //something here that sets the variable to the template
var newdiv = document.createElement("div");
template.appendChild(newdiv);

I found some answers where they treat the template like a string and just splice in the literal string "<div></div>" .

However, I plan to do a lot of modification so treating it as a string will quickly get too confusing, and will be unmaintainable if I do it. If possible, I would like to treat it the same way I treat the page's DOM in regular js.

I am also open to having no template, and just dynamically generating the whole thing in the link function, if it's possible for me to somehow get the directive to return this

Compiled element can be modified in link function . No bindings or directives can be added to the element at this point without recompilation.

...
link: function (scope, element, attrs) {
  // jqLite element that partly implements jQuery API
  element.append(...);

  // native element that is wrapped with jqLite
  var nativeElement = element[0];
  nativeElement.appendChild(...);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM