If I use
<input type="text" value="asdf">
Then I see an input with the default value of asdf
but if I do
<input data-ng-model="modelname" type="text" value="asdf">
Then I can use the modelname
in the controller but the default value no longer shows up. How can I use both things?
Tools:
Typically you would set the default value of modelname inside of a controller. It is possible to cheat a little and use the 'ngInit' directive, though the angular documentation discourages its use outside of ngRepeat.
<input data-ng-model="modelname" data-ng-init="modelname = 'asdf'" type="text">
Relevant statement from angular docs
"The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope."
Set $scope.modelname = "asdf" in your controller. You don't need the value attribute.
Instead of setting the default value of an element that is bound to a model in the view.. it is highly advisable to set these default values within the controller context.
For instance, <input ng-model="yourModelName" type="text">
will need a partner in your controller named $scope.yourModelName = 'whateveryouwant'
.
As soon as the input DOM element has loaded it will check your containing controller for that model and fill it in. This is why two way data binding is great these days. In a real world instance, you can populate a form that contains user details based on a return of an API hit without any mapping.
Just to show you the power.. this returns data and binds it to the scope with an object named myUser
somethingService.getSomething(id).then(function(res) {
$scope.myUser = res.data;
}
You can now initialize fields that the myUser
object COULD contain in the view such as..
<input type="text" ng-model="myUser.name">
<input type="text" ng-model="myUser.address">
<input type="text" ng-model="myUser.gender">
Use this
$scope.foo={};
$scope.foo.modelname = "asdf";
instead of this
$scope.modelname = "asdf"