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是未定義
'$ scope.myFormNg'中的'ng'是什麼? – Sprottenwels
你不應該在尋找$ scope.myFormNg嗎? – Jason