我是AngularJS的新手,正在尝试使用表单名称设置表单字段的默认值。我不知道当我在输入字段中键入错误时,我可以看到下面标题中的值。但是,默认值不是由javascript代码设置的。
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form name="testForm">
<input ng-model="testForm.name">
<h1>My name is {{testForm.name}}</h1>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.testForm = {};
$scope.testForm.name = "John Doe";
});
</script>
<p>When you change the name in the input field, the changes will affect the model, and it will also affect the name property in the controller.</p>
</body>
</html>
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', function($scope){
var vm = this;
vm.testForm = {};
vm.testForm.name = "John Doe";
}])
HTML代码
<div ng-controller="myCtrl as vm">
<form name="testForm">
<input ng-model="vm.testForm.name">
<h1>My name is {{vm.testForm.name}}</h1>
</form>
</div>
plunker链接
将testForm.name更改为简单的name会带来好处:
<div ng-app="myApp" ng-controller="myCtrl">
<form name="testForm">
<input type="text" ng-model="name">
<h1>My name is {{ name }}</h1>
</form>
</div>
<p>When you change the name in the input field, the changes will affect the model, and it will also affect the name property in the controller.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>
我不知道为什么。。因此,如果有人能告诉我为什么我会非常感激:-)
您可以使用ng value="defaulVar"或value="default"来设置默认值。
<input ng-model="testForm.name" ng-value="testForm.name" value="default">
最佳Fabian