Rajagopal Subramanian Rajagopal Subramanian - 4 years ago 729
Javascript Question

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

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 Source

You could have a directive which will take care of setting a default value to ''

Markup

input empty-input ng-model="myInput.name" /> <br> <br>
age: <input empty-input ng-model="myInput.age" />

Directive

.directive('emptyInput', function($parse) {
    return {
      require: '?ngModel',
      link: function(scope, element, attrs, ngModel) {
        //ngModel should be there & it should be of type text
        if (angular.isObject(ngModel) &&
          (!attrs.type || attrs.type === 'text')) {
          var model = $parse(attrs.ngModel);
          model.assign(scope, '');
        }
      }
    }
});

Other thing you could loop through object and make each property to ''. But that has limitation which is, for some property you don't wanted to change the value to ''. Then the directive way would be preferable rather than adding condition inside your loop.

Demo here

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