By Default, How to set ng-model value to an empty string

rajagopalx picture rajagopalx · Dec 23, 2015 · Viewed 8.7k times · Source

Here is my code :

 <div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="myInput.name" />
    age: <input ng-model="myInput.age" />

    <pre>
      {{myInput | json}}
    </pre>
  </div>

  <script type="text/javascript">
    angular.module('myApp', [])
      .controller('myCtrl', function($scope) {
        $scope.myInput = {};
      });
  </script>

By Default, Empty string is not set to ng-model.

By Default, How to set all of the myInput value to "" ?

Here is the plnkr

Update:

Assume There are more than 100 myInput field. Shall I have to manually set it to ' ' ?

Update 2:

Pankaj Parkar directive works well. But Of Course, It set all model value to ' ' . How to set model to empty string only if the model is empty ? I checked attrs.value == undefined but nothing helps.

Answer

jfadich picture jfadich · Dec 23, 2015

there are two ways to do it.

In the controller:

.controller('myCtrl', function($scope) {
    $scope.myINput = {
        name: '',
        age: ''
    };
});

Or in the view

Name: <input ng-model="myInput.name" ng-init="myInput.name=''" />
age: <input ng-model="myInput.age" ng-init="myInput.age=''" />