anatol
anatol

Reputation: 1760

Can't add an attribute to an element using $postLink - AngularJS

I have a simple component and what I'm trying to do is to add to my input element an attribute multiple dynamically but somewhy it doesn't work. Why? And is there any way to do what I want?

app.component('myComponent', {
    templateUrl: 'tmpl.html',
    bindings: {
        str: '@'
    },
    controller: function () {
        var ctrl = this;
        ctrl.$postLink = function () {
            $('#myInputId').attr('multiple', '');
        }
    }
}

Upvotes: 0

Views: 101

Answers (1)

anatol
anatol

Reputation: 1760

This is the solution:

app.component('myComponent', {
    templateUrl: 'tmpl.html',
    bindings: {
        str: '@'
    },
    controller: function ($element) {
        var ctrl = this;
        ctrl.$postLink = function () {
            $element.find('input').attr('multiple', 'multiple');
        }
    }
}

The trick was in linking stuff. Code from the question doesn't work because the input not exists in DOM yet at the time $postLink hook triggered. So what we need is to inject $element service into controller and use it to manipulate DOM.

Upvotes: 0

Related Questions