66

I'm trying to change the value of the input placeholder from a controller but cant quite figure out how.

input(type='text', ng-model='inputText', side='30', placeholder='enter username')

Is there a way to modify a model's element attributes?

Chris
  • 13
  • 6
Jonah Katz
  • 5,230
  • 16
  • 67
  • 90

4 Answers4

136

You can bind with a variable in the controller:

<input type="text" ng-model="inputText" placeholder="{{somePlaceholder}}" />

In the controller:

$scope.somePlaceholder = 'abc';
Wagner Francisco
  • 2,210
  • 1
  • 16
  • 15
  • it works, however, the whole expression is visible to end users for a brief delay. That's why there are ng-binding. See https://docs.angularjs.org/api/ng/directive/ngBind – Bùi Thanh Hải Nov 26 '14 at 02:55
  • 7
    Also, will not work in IE, throwing an error. Presumably same reason why syle="{{}}" is discouraged: https://docs.angularjs.org/guide/ie – velochy Jan 15 '15 at 10:32
  • @BùiThanhHải exactly how would you use ng-bind in this situation? Got a code sample? – Greg Dougherty May 13 '16 at 00:49
  • You example is not working on devices. Keyboard shows but not write – Braian Mellor Aug 24 '16 at 22:13
  • 1
    to accomplish the functionality of ng-bind for attribute use `ng-attr-*attributeName*` as mentioned by [ysub](http://stackoverflow.com/a/37708786/4068027) – Aides Nov 23 '16 at 09:09
21

The accepted answer still threw a Javascript error in IE for me (for Angular 1.2 at least). It is a bug but the workaround is to use ngAttr detailed on https://docs.angularjs.org/guide/interpolation

<input type="text" ng-model="inputText" ng-attr-placeholder="{{somePlaceholder}}" />

Issue: https://github.com/angular/angular.js/issues/5025

ysub
  • 221
  • 2
  • 6
7

Since AngularJS does not have directive DOM manipulations as jQuery does, a proper way to modify attributes of one element will be using directive. Through link function of a directive, you have access to both element and its attributes.

Wrapping you whole input inside one directive, you can still introduce ng-model's methods through controller property.

This method will help to decouple the logic of ngmodel with placeholder from controller. If there is no logic between them, you can definitely go as Wagner Francisco said.

Z.T. Yang
  • 342
  • 1
  • 5
5

As Wagner Francisco said, (in JADE)

input(type="text", ng-model="someModel", placeholder="{{someScopeVariable}}")`

And in your controller :

$scope.someScopeVariable = 'somevalue'
Frozen Crayon
  • 5,172
  • 8
  • 36
  • 71
amit_kenny
  • 119
  • 1
  • 2