2016-05-03 14 views
0

AngularJSを初めて使用し、フォーム名を使用してフォームフィールドのデフォルト値を設定しようとしています。私は入力フィールドに入力すると何が間違っているのかわからないので、私は下の見出しの値を見ることができます。しかし、デフォルト値はjavascriptコードで設定されていません。デフォルトでanglejsにフォームフィールド値を設定できません

<!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>

答えて

1
var app = angular.module('myApp', []); 
     app.controller('myCtrl', ['$scope', function($scope){ 
      var vm = this; 
      vm.testForm = {}; 
      vm.testForm.name = "John Doe"; 
     }]) 

HTMLコード

:-)非常に感謝されるでしょう

plunker link

+0

ありがとう、これは働いた。しかし、なぜ私たちはこれを行う必要がありますか...私はそれが$範囲で直接動作しなかった理由を意味します。 –

+0

このhttps://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#controllersをお読みください –

0

デフォルトを設定するには、NG-値= "defaulVar" または値= "default" を使用することができます。

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

ベスト ファビアン

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> 

私はなぜ..soアイデアを持っていません

+0

<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> 
私は同じフィールド名を持つと同じコントローラ内部の二つの形式を持っている場合。これは使えますか? –

関連する問題