0

So I've looked at many other questions like this and haven't found one that quite seems to cover what I'm trying to do.

I'm using a template in a directive to create a custom dropdown with fancy stuff like a search box. For this, I have to use template; I can't just use compile with element.replaceWith (I'm able to get this working if I use compile with an attrs param, but then the custom template doesn't work).

All I want to do is select a particular array of options depending on the contents of an attribute in my custom tag:

HTML: <customdropdown useoptionset="first"></customdropdown>

JS:

angular.module('ui.bootstrap', [])

.constant('customdropdownConfig', {
    //bunch of properties here
})

.directive('customdropdown ', ['$parse', 'customdropdownConfig', function ($compile, customdropdownConfig) {
    return {
        restrict: 'EA',
        replace: true,
        template: (function(conf) {
            var optionset = //how can i access the useoptionset attribute here?

            var options = //stuff involving useoptionset and conf

            return '<select ui-select="customDropdown">' + options + '</select>';
        }(customdropdownConfig))
    };
}])

It seems to me that this should be a very common and obvious use case, but maybe I'm missing something about how Angular works.

1 Answer 1

1

Try making the template much more simple and then using the linking function to add dynamic content to the <select> element.

Like this:

.directive('customdropdown ', ['$parse', 'customdropdownConfig', function ($compile, customdropdownConfig) {
    return {
        restrict: 'EA',
        replace: true,
        template: '<select ui-select="customDropdown"></select>',
        link: function(scope, elem, attrs){
            var optionset = attrs.optionset;
            var options = //stuff involving useoptionset and conf
            elem.html(options);
            $compile(elem.contents())(scope);
        }
    };
}]);

It sounds like you may have tried this already, but I can't see why it wouldn't work. If it doesn't, maybe you could give more explanation of what you've tried so far and why it hasn't worked.

Sign up to request clarification or add additional context in comments.

1 Comment

probably the reason i couldn't get it to work was that i'm still relatively new to angular and wasn't really sure how to use templates and linking functions (looks like i was trying to combine the functionality of both into template). it's amazing how much your example alone clears things up - thanks, i'm sure that will work. i'll give this a shot tomorrow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.