Aron
Aron

Reputation: 9246

Changing placeholder via AngularJS directive?

I have a text input field whose placeholder I want to change every few seconds. However I don't want to pollute my controller with this so I want to encapsulate this functionality into a directive.

This is what my directive looks like:

myApp.directive('searchBox', ['$interval', function($interval) {
    return {
        restrict: 'A',
        link(scope, element, attrs) {
            $interval(function() {
                attrs.placeholder = 'New';
            }, 1000);
        }
    }
}])

And the html:

<input type="text" class="form-control" placeholder="Old" ng-model="search" search-box>

However the placeholder stubbornly doesn't change, even though in the console attrs.placeholder can be seen to change to 'Test' from 'Hello'. Any ideas?

PLUNKR: https://plnkr.co/edit/Oy1M8FPTXxzB9oYMJqlx?p=preview

Upvotes: 1

Views: 1791

Answers (1)

Iso
Iso

Reputation: 3238

You cannot change attributes values via the attr object (it's just a static reflection of your element attributes). Instead, update your element using element.attr('placeholder', 'Test') or attrs.$set('placeholder', 'Test').

Upvotes: 2

Related Questions