panagulis72 panagulis72 -3 years ago 173
AngularJS Question

Empty the placeholder when using ng-model

I'd like to create a

text input
linking it to a variable in the Scope. But I don't want the
placeholder
display anything. However the content of this variable in scope continues to shows. Why?



var app = angular.module('example', []);

app.controller('MainCtrl', function($scope) {
$scope.hello = 'hello';
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="example" ng-controller="MainCtrl">
<input type="text" ng-model="hello" placeholder="">
</body>




Answer Source

You have a variable in scope, called hello. You have an <input> element which is bound to the same variable. Inevitably, the element will have the same value of that variable.

As I understand from your comments, you wish the input element not to be bound to that variable. In this case, there are several alternatives. One for example is to have a separate variable in your scope.

Then you can use ngChange to update the first variable only if the input is changed, and thus maintain the initial value of it.

var app = angular.module('example', []);

app.controller('MainCtrl', function($scope) {
  $scope.hello = 'hello';
  $scope.field = '';
  $scope.change = function() {
    $scope.hello = $scope.field;
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body  ng-app="example" ng-controller="MainCtrl">
    <input type="text" ng-model="hello" ng-change="change()">
</body>

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