Html AngularJS:如何将默认值设置为 ng-model="searchText"?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30481366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS: How to set default value to ng-model="searchText"?
提问by Sachin B. R.
I am unable to set a default value to ng-model="searchText". Here is the code I am using<input ng-model="searchText" value="can you see me" />
我无法将默认值设置为 ng-model="searchText"。这是我正在使用的代码<input ng-model="searchText" value="can you see me" />
Can anyone help me with this?
谁能帮我这个?
回答by Marwen Cherif
1st Solution:is to simply init the searchText in the controller.
第一个解决方案:简单地在控制器中初始化 searchText。
App.controller('mainController',['$scope', function($scope) {
$scope.searchText = "can you see me";
}]);
2nd Solution:is to use ng-init insteat of value
第二种解决方案:是使用 ng-init 代替值
<input ng-model="searchText" ng-init="searchText ='can you see me'"></input>
回答by Ashish Mehta
<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
您可以使用 ng-init
回答by carton
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>
回答by Joshua Kelly
Do not use ng-init on your input field to set the value. That's not required.
不要在输入字段上使用 ng-init 来设置值。那不是必需的。
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.
只需将模型的范围设置为您想要的值。如果它只是占位符文本,最好在输入元素上使用 html5 占位符属性。
<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";
回答by C.P.
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.
并将输入标签上的 value 属性保留为空白。