Reputation: 2313
I have ng-model attached to , but i want to display a default placeholder value if it's not been touched ($pristine
). Is there any good way to do it? I cannot simply set my ng-model value to null during initial.
Here's my plunker:
http://plnkr.co/edit/0kzKrwKTbJzsMGG8D1gQ?p=preview
<body ng-controller="inputController">
<input type="number" id="pricefield" min="0" name="price" placeholder="Price" ng-model="test.value" required/>
</body>
angular.module('plunker', []);
function inputController($scope) {
$scope.test = {value: 0};
}
Upvotes: 2
Views: 1332
Reputation: 136184
You could use ng-attr
directive to set placeholder value dynamically, to check the form element is pristine
or not you need to place this field inside a form
& then you could easily check the $pristine
property of that form element like myForm.price.$pristine
.
Markup
<form name="myForm">
<input type="number" id="pricefield" min="0" name="price" ng-model="test.value"
ng-attr-placeholder="{{myForm.price.$pristine ? 'Some Value': 'Default Value'}}" required/>
</form>
Update
I'd suggest to have one directive that will change hide the $viewValue
on initial load & will show placeholder. Directive will have controller over the display value using $formatters
on ngModelControlller
Markup
<input type="number" custom-dir id="pricefield" min="0" name="price"
ng-attr-placeholder="{{myForm.price.$pristine ? 'Initial Placeholder': 'After change Placeholder'}}"
ng-model="test.value" required/>
Directive
app.directive('hideInitialLoad', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
var initalHide = true;
//format text going to user (model to view)
ngModel.$formatters.push(function(value) {
console.log(attr.min > value)
if (initalHide){
initalHide = false;
return undefined;
}
return value;
});
}
};
});
Upvotes: 1