Denis Gvozd
Denis Gvozd

Reputation: 33

“replace: true” with ng-if in angular directive

I created new custom angularjs directive (d-emails). The template of this directive contains "ng-if" directive. And in this directive we can see "replace: true". The main reason of this - just because I want to check user role inside of the directive and then if user doesn't have an appropriate role to remove whole element from html. I don't want to leave element with class="col-sm-6" inside html. But when I wrote this code I realize that in this case I can't use isolated scope. Ng-if removed my isolated scope and added new scope inherited from the parent scope. Any suggestions how to manage this situation? I saw the similar questions like this Issue with isolated scope and "replace: true" in angular directive but I couldn't find any appropriate solutions.

function dEmails() {
    var directive = {
        scope: {},
        bindToController: {
            entityId: "=",
            entityType: "="
        },
        controllerAs: "vm",
        templateUrl: "/directives/d-emails.tmpl.html",
        restrict: "E",
        controller: dEmailsController,
        replace: true
    };
    return directive;
}

dEmailsController.$inject = ['roleService'];

function dEmailsController(roleService) {
    var vm = this;
    init();
    var roleId = 4;
    vm.isApproved = false;

    function init() {
        roleService.hasRole(roleId).then(function(isApproved) {
            vm.isApproved = isApproved;
            if (isApproved) {
                emailResource.get({ entityId: vm.entityId, entityType: vm.entityType }).$promise.then(function(response) {
                    vm.list = response.Result;                        
                });
            }
        });
    }
}

Where d-emails.tmpl.html looks like this:

<div class="email-item" ng-if="vm.isApproved">
    <div>Content of my super directive</div>
</div>

And code where I use this directive:

<d-emails class="col-sm-6" entity-id="vm.entityId" entity-type="vm.entityType.event">
</d-emails>

Upvotes: 1

Views: 1322

Answers (1)

Łukasz Staniszewski
Łukasz Staniszewski

Reputation: 668

Instead of using ng-if just remove element in directive when vm.isApproved is false.

Upvotes: 1

Related Questions