Aron Aron - 1 year ago 128
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
Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download