Aron Aron - 4 months ago 10
AngularJS Question

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
can be seen to change to 'Test' from 'Hello'. Any ideas?


Iso Iso

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').