Scottie
Scottie

Reputation: 11308

Using model binding in my angular directive

I am beginning to learn Angular and so far I'm in love with it!

I have the following directive snippet:

app.directive('validation', function() {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            element.after("<div name='" + attrs.ngModel + "'></div>");
        }
    };
});

Formulating a div like this doesn't seem to be the right approach. I would think that I should do something more along the lines of:

element.after("<div name='{{attrs.ngModel}}'></div>");

but I can't quite figure out the right syntax.

Also, does this need to be compiled?

Upvotes: 0

Views: 37

Answers (1)

rob
rob

Reputation: 18513

You can use template or templateUrl to get some dynamic HTML like this.

app.directive('validation', function() {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            scope.myModel = attrs.ngModel;
        },
        template: '<div name="{{myModel}}"></div>'
    };
});

Note that using ngModel can be a bit more complicated than just using some other arbitrary attribute on your element. Checkout the ngModel vieo on egghead io for more info https://egghead.io/lessons/angularjs-using-ngmodel-in-custom-directives

Upvotes: 1

Related Questions