Jack Parkinson
Jack Parkinson

Reputation: 711

Checking Input to a Custom Directive in AngularJS

I have a very large form, which was getting difficult to read and follow when editing the HTML. I decided that I would try and make the most of AngularJS and use custom directives to compress the amount of repeated text. Here is the original directive I wrote:

app.directive("formField", function () {
    return {
        restrict: 'E',
        scope: {
            fieldData: '=field',
            fieldName: '=name',
            fieldType: '=type'
        },
        template: <SOME HTML>
    }
});

And I would use this directive to add form fields to my page as follows:

<form-field field="some_data" type="text" name="other_data"></form-field>

I was using the type variable to differentiate between dateTime input, text input, numbers, etc, as they were distinguished in my code by only one keyword (by the input's type attribute.)

However now I have encountered a need to include checkboxes, which, thanks to my layout, require significantly different code to be structured properly. Based on this, when the type "checkbox" is passed into the directive I would like to return a different template value. I have tried variations of this kind of thing:

app.directive("formField", function () {
    return {
        restrict: 'E',
        scope: {
            fieldData: '=field',
            fieldName: '=name',
            fieldType: '=type'
        },
        template: function () {
            if(fieldType == 'checkbox') {
                return <CHECKBOX HTML>;
            } else {
                return <REGULAR FIELD HTML>;
        }
    }
});

This doesn't work. Can anybody tell me how to check the value coming in for the type field so that I can compare it in the directive's returned object? Thanks.

Upvotes: 1

Views: 64

Answers (1)

Daniel W.
Daniel W.

Reputation: 563

In the template, you can check for the element's attributes.

Your template should look like:

template: function (element, attrs) {
        if(attrs.type == 'checkbox') {
            return <CHECKBOX HTML>;
        } else {
            return <REGULAR FIELD HTML>;
        }
    }

The isolate scope attribute definitions for fieldData, fieldName, and fieldType are available in the template return string (using expressions), but they are not available in the template's logic. Ex:

template: '<p>{{ fieldData }}</p>'

Upvotes: 1

Related Questions