默认情况下,无法在angularjs中设置表单字段值

时间:2016-05-03 04:57:56

标签: angularjs

我是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>

3 个答案:

答案 0 :(得分:1)

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 link

答案 1 :(得分:0)

您可以使用ng-value =“defaulVar”或value =“default”来设置默认值。

<input ng-model="testForm.name" ng-value="testForm.name" value="default">
最佳

费边

答案 2 :(得分:0)

将testForm.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>

我不知道为什么..如果有人能告诉我为什么我会非常感激: - )