0

I have a simple view problem that I may have made more difficult by trying to create my first directive in Angular. I have this service that returns an array of user roles for the current user. Many users are only going to have the user role. With that in mind I don't want to display anything on their profile page. However, some people like myself will have User and Admin roles. So on the profile page I would like to display a drop down to change the current role.

I thought I'd create a directive that did a check basically

if user.roles.length != 1 then show drop down else remove the element from the dom.

Like I said before I have never created a directive before and they seem like the right way to go but I am not getting the result I would like.

I have this:

app.directive('selector', function (SessionState, $compile) {
    return {
        priority: 100000,
        scope: false,
        compile: function (element, attr, linker) {

            var data = SessionState.User.Data.roles;

            var multiRoleView = '<p>Active Role:</p><select ng-model="State.User.activeRole" ng-options="role for role in data"></select>';

            if (data.length != 1) {
                element.html(multiRoleView).show();
                $compile(element.contents());
            } else {
                element.children.remove();
                element.remove();
            }

            return function linkFn() {
                /* Optional */
            }
        }
    }
});

This will render the html correctly depending on if that user should see it, but for admins it doesn't display any roles because I am assuming my data variable is never being used.

1 Answer 1

1

I hate to post a bad question but with some fiddling around and reading the documentation for $compile I found that by setting the scope variable to true. I could simply use the parents scope and that made everything very easy.

The completed and correct code:

Live link: https://app.baileysproject.com

Set scope to true, uses parents scope. Removed the element.children.remove(), throws errors.

app.directive('selector', function (SessionState, $compile) {
return {
    priority: 100000,
    scope: true,
    compile: function (element, attr, linker) {



        var multiRoleView = '<p>Active Role:</p><select ng-model="State.User.activeRole" ng-options="role for role in State.User.Data.roles"></select>';

        if (data.length != 1) {
            element.html(multiRoleView).show();
            $compile(element.contents());
        } else {
            element.remove();
        }

        return function linkFn() {
            /* Optional */
        }
    }
}
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.