Chris Chris - 1 year ago 142
AngularJS Question

Delay creation directive

I am looking to create a delayed creation directive such that I can simply add it to an object like so to allow it to be created some time later like so

<div delay-creation="1000">Theres lots of things in here </div>

The reason behind this is that my UI is quite complicated and lots of objects are rendered that arent initially seen. I see this as a nice reusable way to delay creation of off screen objects without having to mess about with custom code all the time.

I initially thought my new directive could conditionally adding
to the
and then, after some time period, set the value to be
. Unfortunately this seems far more complicated than I first thought. Is there a better way to do this or can anyone help me in creating this directive?

** Edit: Based off of Bens code this now works **

export class DelayCreationDirective implements angular.IDirective {

restrict = "A";

public link: (scope: angular.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void;

constructor($timeout: angular.ITimeoutService) { = ($scope: angular.IScope, $element: angular.IAugmentedJQuery, attrs: ng.IAttributes) => {

var placeholder = angular.element(document.createComment("delayCreation placeholder"));


$timeout(() => {
$element.attr("ng-if", $attrs["delayCreation"]);

if (placeholder) {

}, 1000);

static factory(): ng.IDirectiveFactory {
const directive = ($timeout: angular.ITimeoutService) => new DelayCreationDirective($timeout);

directive.$inject = ["$timeout"];

return directive;

.directive("delayCreation", DelayCreationDirective.factory());

Answer Source

I think that using ng-if won't help you because Angular's ng-if DOM sub-tree always gets complied, then removed from DOM if needed. So it takes the time anyway.. We implemented in the past a "lazy-ng-if" directive, to prevent that complication, maybe it can be used in your UC?

BTW, this capability was added to Angular1.5 as well AFAIK

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download