uriDium
uriDium

Reputation: 13420

Is the compile method appropriate for altering the template dynamically in a directive?

I have a directive where I want to add a select and either a textarea or an input field depending on some input. For example

app.directive('monkey', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div><select><option>1</option><textarea>{{text}}</textarea></div>'
        scope: {
            text: "="
        },
        link: function(element, attrs, scope) {

            // Add listeners etc

        }
    }
});

so the html would look something like

<monkey text="model.name" type="input"></monkey>

I want to be able to look at the type attribute and change my template from

<div><select><option>1</option><textarea>{{text}}</textarea></div>

to

<div><select><option>1</option><input>{{text}}</input></div>

Is the compile function what I should be using?

Upvotes: 0

Views: 48

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67296

Yes, you could use the compile method for this.

But, if you have a limited set, I would opt for ng-if first. Just because it keeps things slightly more simple.

So the template becomes something like:

<div><select><option>1</option><textarea ng-if="type == 'textarea'">{{text}}</textarea><input ng-if="type == 'input'">{{text}}</input></div>

So, you would need to take type into your directive as well. Here is the entire directive:

app.directive('monkey', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div><select><option>1</option><textarea ng-if="type == 'textarea'">{{text}}</textarea><input ng-if="type == 'input'">{{text}}</input></div>'
        scope: {
            text: "=",
            type: "@"
        },
        link: function(element, attrs, scope) {

            // Add listeners etc

        }
    }
});

Upvotes: 1

Related Questions