AlexB
AlexB

Reputation: 4528

Angularjs directive dynamic html replace element and ng-if

I have my custom directive which is defined like this:

.directive("myDirective", [
    return {
        restrict: "E",
        replace: true,
        terminal: true, // otherwise we won't be able to compile a template
        controller: "MyCtrl",
        scope: {
        ...
        },
        
        compile: function (element, attrs) {
            element.html("");
            element.removeClass();

            ...

            return {
            post: function (scope, iElement, iAttrs, controller) {
                loadTemplate(templUrl).then(function (templateElement) {
                //iElement.replaceWith(templateElement);
                iElement.append(templateElement);
                var teLinkingFn = $compile(templateElement);
                teLinkingFn(scope);
                var modal = $("div.modal", templateElement);
                if (modal.length > 0) {
                    scope._modal = modal;
                    templateElement.removeClass();
                    if (iAttrs.class) {
                        $("button", templateElement).eq(0).addClass(iAttrs.class);
                    }
                }
            });
...

Now, I use it with ng-if:

<my-directive ... ng-if="some_criteria"/>

The problem is when I replace original element and some_criteria changes I still have my custom html visible. But if I append to the directive it works (disappears). How can I resolve this?

Upvotes: 1

Views: 1484

Answers (1)

robert.bo.roth
robert.bo.roth

Reputation: 1353

When you replace the original markup <my-directive ... ng-if="some_criteria"/> with whatever's loaded in your template file, you lose the ng-if directive from that original markup. You can either add an ng-if on your template file, or, you can just not use the replace functionality.

Is there a particular reason you want it to be replaced?

Upvotes: 1

Related Questions