Change value of input placeholder via model?

AngularjsPug

Angularjs Problem Overview


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?

Angularjs Solutions


Solution 1 - Angularjs

You can bind with a variable in the controller:

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

In the controller:

$scope.somePlaceholder = 'abc';

Solution 2 - Angularjs

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

Solution 3 - Angularjs

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.

Solution 4 - Angularjs

As Wagner Francisco said, (in JADE)

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

And in your controller :

$scope.someScopeVariable = 'somevalue'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonah KatzView Question on Stackoverflow
Solution 1 - AngularjsWagner FranciscoView Answer on Stackoverflow
Solution 2 - AngularjsysubView Answer on Stackoverflow
Solution 3 - AngularjsZ.T. YangView Answer on Stackoverflow
Solution 4 - Angularjsamit_kennyView Answer on Stackoverflow