How to set the initial value of ng-model to an empty string in angularjs?

stcho picture stcho · Aug 1, 2014 · Viewed 30.9k times · Source

I want to be able to set my initial value for an attribute of my model as such

<input type="text" ng-model="selectedModel.title" name="title" value="" >

As shown above, I want the value of the attribute to be an empty string as to initially instantiate the input text field with an empty string.

However, currently the ng-model="selectedModel.title" overrides the value="".

How do I get past this?

Answer

user9903 picture user9903 · Aug 1, 2014

Set initial values in the controller

You should do this in your controller:

angular.module('MyModule').controller(
  'myController',
  function ($scope, MyService) {
    $scope.selectedModel = { title: '' };
  }

  // if you're using a service
  MyService.getModel().then(function (model) {
    $scope.selectedModel = model;
    // selected model doesn't have a title set, so give it a blank string as default
    if (angular.isUndefined($scope.selectedModel)) {
      $scope.selectedModel.title = '';
    }
  });
);

You can read more about setting the initial state of $scope in your controller here.

Other Option: ng-init

The official AngularJS docs for ng-init suggest that there is only one use for ng-init, "for aliasing special properties of ngRepeat". In your case you're better off using the controller to initialize the value.

You can use ng-init:

<input type="text"
       name="brand"
       ng-model="selectedModel.title"
       ng-init="selectedModel.title=''">
</input>