Skip to content Skip to sidebar Skip to footer

AngularJS: How To Set Default Value To Ng-model="searchText"?

I am unable to set a default value to ng-model='searchText'. Here is the code I am using Can anyone help me with this?

Solution 1:

1st Answer : is to simply init the searchText in the controller.

App.controller('mainController',['$scope', function($scope) {
   $scope.searchText  = "can you see me";
}]);

2nd Solution: is to use ng-init insteat of value

<input ng-model="searchText" ng-init="searchText ='can you see me'"></input>

Solution 2:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="">
<div >
  <input ng-model="searchText" type="text" ng-init="searchText='your text'"/>
</div>  
  </div>  

you can use ng-init


Solution 3:

Try this following code:

     <input ng-model="searchText" ></input>

In your controller

    $scope.searchText = "your default value";

Edit : If you don't want to initialize the default value in controller just do

      <input value="your default value" ></input>

Solution 4:

Do not use ng-init on your input field to set the value. That's not required.

Just set the scope of your model to the value you would like. If it's simply placeholder text, it would be better to use the html5 placeholder attribute on your input element.

<input type="text" ng-model="someText" placeholder="Initial Text">

This will give you some text in the input field without the need to add anything to the controller scope.

If you want the text as a value you can pass without filling in the input field than you would need to set that in your controller.

$scope.someText = "Some Text";

Solution 5:

You can set default value in the controller. Like this:

app.controller('myCtrl', function($scope){
   $scope.searchText = "Some default value";
});

And keep value attribute blank on input tag.


Post a Comment for "AngularJS: How To Set Default Value To Ng-model="searchText"?"