2014-01-24 77 views
1

我目前正在玩AngularJS,我試圖讓表單驗證工作。我讀到,如果你給表單一個名稱屬性,那麼表單的ngFormController將作爲一個屬性出現在$ scope對象上。但我似乎無法得到那個工作。這是我到目前爲止的代碼:

<body ng-app="myapp"> 

<div ng-controller="MyController" > 
<form name="myFormNg" ng-submit="myForm.submitTheForm()" novalidate> 
    <input type="text" id="name" ng-model="myForm.name" ng-minlength="5" ng-maxlength="12"> Name <br/> 

    <select multiple="true" 
      ng-model="myForm.car" ng-options="obj.id as obj.name group by obj.type for obj in myForm.options"> 
     <option value="" >Please choose a car</option> 
    </select> 

    <input type="submit" value="Submit Form 2"> 
</form> 

</div> 

<script> 
angular.module("myapp", []) 
    .controller("MyController", function($scope, $http) { 
     $scope.myForm = {}; 
     $scope.myForm.name = "Jakob Jenkov"; 
     $scope.myForm.car = ["nissan", "toyota"]; 

     $scope.myForm.options = [ 
      { id : "nissan", name: "Nissan", type : "4 Door" } 
      , { id : "toyota", name: "Toyota", type : "4 Door" } 
      , { id : "fiat" , name: "Fiat" , type : "2 Door" } 
     ]; 

     for(field in $scope) { 
      console.log(" $scope." + field); 
     } 

     console.log("form: (pristine: " + $scope.myFormNg.$pristine + ", dirty: " + $scope.myFormNg.dirty + 
        ", valid: " + $scope.myFormNg.$valid + ", " + $scope.myFormNg.$invalid + ")"); 

     $scope.myForm.submitTheForm = function(item, event) { 
      console.log("--> Submitting form"); 
      var dataObject = { 
       name : $scope.myForm.name 
       ,car : $scope.myForm.car 
      }; 

      var responsePromise = $http.post("/angularjs-examples/json-test-data.jsp", dataObject, {}); 
      responsePromise.success(function(dataFromServer, status, headers, config) { 
       console.log(dataFromServer.title); 
      }); 
      responsePromise.error(function(data, status, headers, config) { 
       alert("Submitting form failed!"); 
      }); 
     } 

    }); 
</script> 

我得到的JavaScript控制檯以下錯誤信息:

「錯誤:$ scope.myFormNg是未定義

+0

'$ scope.myFormNg'中的'ng'是什麼? – Sprottenwels

+0

你不應該在尋找$ scope.myFormNg嗎? – Jason

回答

1

您試圖期間訪問的FormController 。實例myController的,但在這個時候的FormController尚未實例化並綁定到$範圍

試試這個:

console.log("form: (pristine: " + $scope.myFormNg.$pristine + ", dirty: " + $scope.myFormNg.dirty + 
        ", valid: " + $scope.myFormNg.$valid + ", " + $scope.myFormNg.$invalid + ")") 

在控制器方法 - 例如在您submitTheForm函數。

+0

我將代碼移到了$ scope.checkForm()函數中,然後它就起作用了。謝謝! –