AngularJS - 无法将ngFormController附加到$ scope

时间:2014-01-24 14:26:19

标签: javascript angularjs

我目前正在玩AngularJS,我正在努力让表单验证工作。我读到如果你给表单一个name属性,那么表单的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未定义

1 个答案:

答案 0 :(得分:1)

您正在尝试在MyController实例化期间访问FormController。但此时FormController尚未实例化并绑定到$ scope。

试试这个:

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

在控制器方法中 - 例如在submitTheForm函数中。